At what level to apply functional programming approach [closed] - functional-programming

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Should one apply functional programming practices at the design level, i.e. when we identify and design class hierarchy, or is it applicable only when it comes to writing function bodies?
What I feel is that we do the design process applying normal OOPs techniques and write implementations using a functional approach.
Your thoughts, please!

The design process should be OOP agnostic. Maybe we'll need objects and classes, maybe we won't. Maybe a large portion will use functional techniques. Maybe all it needs is a 5 minute perl script. It depends on what we're trying to accomplish.
That said, an argument could be made that OOP may get in the way of a purely functional design. Other arguments could be made that it doesn't. Another argument could be made that you just need to use your best judgement and balance the two paradigms. Others will chime in and say the two approaches are orthogonal and can be combined without conflict.
But it's all abstract really. The answer is MU. Pose a real problem you have, and then we'll be able to tell you whether a functional or oop approach is appropriate, and at what level.

Brian McNamara, of the F# Development team, has an interesting blog titled How does functional programming affect the structure of your code?.
I tend to agree with his assessment that functional programming tends to have the largest influence on actual code structure, at the level of implementation and individual routines, and less influence on overall architecture, at the level of modules and subsystems.
That said, I also think that FP can influence how the problem is attacked, and can often lead to entirely different approaches, such as DSL's, async code, filter graphs, actors, etc., but these can all be considered "in the medium" solutions which don't effect the larger architecture, such as distributed, REST, client-server, etc.

I am a bit biased towards the FP approach at design if you want to implement in FP.
But, Breton makes a good point that the selection is subjective.
References.
Another Stackoverflow question: How can I use functional programming in the real world?.
JavaScript: Use functional programming techniques to write elegant JavaScript
F# primer: Use Functional Programming Techniques in the .NET Framework
Discussion thread: Why people don't use functional programming?
Links: list of functional programs applied to real-world tasks

I agree that an OOP high-level decomposition with FP implementation techniques is a good strategy; I discuss this some in a blog:
How does functional programming affect the structure of your code?

Related

Why choose Lisp for a project? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I am seeking concrete and unique features that Lisp (any dialect) offers to a project, compared to the other primarily functional languages.
For example, Haskell offers lazy-evaluation, purity and a type-system which helps build more correct programs. Erlang makes concurrent programming easier by using message passing exclusively, lightweight processes, and so on.
What does LISP bring to the table? What makes it a better suite than other languages for certain projects? What are its features that the other languages lack to make it suitable?
I am not bashing at Lisp; I want to learn more about it and what advantages it offers if used today. Please be specific :)
When I asked my self questions similar to yours, I searched and found this article:
http://www.defmacro.org/ramblings/lisp.html
It doesn't go too much into details, but gives a coarse picture of why Lisp makes sense. I found it very useful (and the whole http://www.defmacro.org/ site for that matter - like the posts there a lot, e.g. this one).
Haskell offers lazy evaluation
Clojure sequence functions are lazy. You can work with infinite lists just like in haskell:
(take 10 (cycle ["odd" "even"]))
purity
Clojure types are immutable. That makes large parts of your program pure without forcing you to climb the ivory tower :) Plus it has STM, just like haskell.
and a type-system
Unfortunately here lisps cannot compete with haskell. Mosts lisps are dynamic.
But dynamic nature of lisps and their VM (image) makes them an awesome choice for a server side programs, like web applications. It is very easy to connect to a running instance of your web app, and change functions or even entire modules on the fly, without restarting application or kicking out users. That is either not possible or very cumbersome with haskell.
Most lisps provide a very easy way to write macros. You write macros in the same language.
With Haskell you will have to learn yet another language (Template Haskell) which is much more complicated and to this day is not even properly documented. You will have a hard time learning it.
Having said that, i use and love both lisp (clojure) and haskell. I prefer haskell because it has the most powerful type system of any available for practical development language.
Plus it bends your mind better than mushrooms :)
Scheme provides hygenic macros and continuations. I'm not sure what other fp languages also provide these features.

advantages of stateful programming? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
i was wondering about the benefits of stateless programming, and found someone who shared my question:
Advantages of stateless programming?
as i read through the answers though, it made me curious about the converse question. what are the advantages of stateful programming? seems like there's a lot of focus on stateless code recently but i'm wary of trends.
it seems that stateful (i.e. imperative) programming might lend itself to certain scenarios better than stateless (i.e. functional) programming, and i'd like to be better able to recognize which problems can be solved by stateful programming.
There are only a few cases where there are non-debatable advantages to a programming model based on mutable, shared state compared to an immutable, stateless programming model. One area where mutability can bring huge advantages is in allowing algorithms to work in-place. The haskell wiki has a great example about implementing quicksort: http://www.haskell.org/haskellwiki/Introduction#When_C_is_better
To summarize it, when you do not allow modifications to the lists memory, you need to create a sorted copy of it. The same is true for almost any other algorithm that modifies some data-structure, e.g. an AVL Tree.
In general, functional programming languages tend to be more memory-intensive than their imperative counterparts. Memory is cheap nowadays, however bandwith is crucial and memory speeds are not increasing proportional to the increase we see in CPU power. It must be noted however, that the execution model of Haskell allows the Compiler to perform some nifty optimizations, also in regard to memory usage and access patterns. To some extent, this can compensate for the theoretical disadvantages.
Legibility is key. I like functional programming (currently I'm on a clojure binge), but state is how the world works. It's no accident that the Object Oriented paradigm is more popular than functional or any other type of programming. OOP and procedural programming are the path of least resistance for new programmers. Most people intuitively understand the idea of an object as something that changes state (it can be moving, or change color, etc.) rather than the Y-combinator that helps with recursion.
State is important. Every bit in this universe have state, it is the state that defines how a system behave, the state makes the system dynamic and usable, but as state is so important it is also important that how this state is accessed and manipulated. It would not be good if any human can manipulate the state of other human (state as an the content in the brain of a human).
My view on state is that it should be made explicit and should not be something that is scattered across your code and become very implicit that it is hard to know what state the system is in and which part of the system is responsible for which part of the state. State should be controlled in such a way that you can easily say that this part of the state of the system is handled by this module and only this module.
In any real world FP program it will always have 2 parts, one which is stateless that would be you core algorithm etc and other part which will maintain the state of the program.

A prototyping language with the ability to be fast [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
as an engineering student with a strong mathemathical background, i dealing some problems like this at university:
(numerical) Simulations
AI Problems
Robotics
Control Systems
and some more
as you can see some are just numerical ones, others have to process some kinds of symbols.
currently i'm working with java, but i'm not very pleased with it (can't say exactly why, probably a personal taste) and now i'm searching for a programming language, in which i can easily prototype new algorithms, like for example in python, and don't care about low level stuff, but has the ability to speed things up if neccessary, e.g. with concurrent/parallel programming, etc. (writing it in python and rewrite it in C/C++ isn't really a option i prefer...)
to sum it up:
easy to prototype, but
the ability to speed algorithms up
syntax without boilerplate stuff like in java
syntax which is easy to read (i know this could be achived with the most, but some language encourage you more...)
i've looked around at sites, like http://rosettacode.org/ and picked 2 or 3 favorites: Go, Lisp (and maybe Haskell) but other recommandations are welcome
Common Lisp using SBCL is pretty fast if you take the time to make it fast.
Why does this fit what you want?
symbolic computations
good number handling
compiles to native on demand by default.
I would use python together with cython: http://www.cython.org for speeding up your code. For symbolic computations you have http://code.google.com/p/sympy/
Try Clojure; it fulfills most of your requirements.
Uses Java libraries, compiles to Java bytecode, and has plugins for Java IDEs, so some of your existing knowledge about Java and its ecosystem will come in handy.
Very concise, readable, and ease of prototyping is extremely high.
Great support for different concurrency strategies.
Performance is getting better fast; typical stuff is within a speed factor of 2 of Java, and slow things can typically be made fast with minimally confounding changes (e.g. a few type hints here and there to use Java primitives.)
An alternative to Common Lisp would be a implementation of scheme. My favorite so far is Racket.
http://racket-lang.org/
When I first got into Lisp I started with scheme and ended up being able to learn it within a matter of days. Also Lisp-wise Racket is a pretty complete language and has a decent IDE in DrRacket.
How about F#?
F# is a remarkable language for prototyping for the following reasons:
F# has an interactive mode allowing you to evaluate blocks of code directly, without compiling your entire project.
Type inference helps keep code small, and makes refactoring your type hierarchy relatively painless. This may not be so important in production code, but I found that to be very valuable during prototyping.
F# integration with .NET makes it easy to prototype extensions of your existing products. In the all-too-common case when a prototype becomes a product (due to time constraints), it's also easy to integrate your F# code within your .NET product.
If prototyping makes up a significant part of your overall development process, then F# can really help you speed up your coding.
I don't think F# will produce code that is significantly faster than other .NET languages. The functional style of programming, in particular purity (no side-effects), can be applied to other programming languages, meaning it is just as easy to write concurrent programs in other languages as well. It does however "feel more natural" to do so in F#.
F# has the Option type, which can be used in place of null values. Code reliability with respect to null-pointer exceptions can be guaranteed at compile time, which is a huge benefit.
Finally, be advised that F# is still in development, and suffers issues, some of which may disappear over time, but not all. See for instance what devhawk and Oliver Sturm have to say about it (in particular about linear scoping and interdependent classes, other issues like overloading, better Visual Studio integration have already been addressed).
this is stated in article: https://stackoverflow.com/questions/328329/why-should-i-use-f
by JOH

Functional Programming: Best Platform/Environment [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have been researching and playing with functional programming lately, solely to broaden my thinking about programming, because I find thinking "functionally" difficult.
I have downloaded Glasgow Haskell and experimented with that.
What I am wondering is, what is the best platform for Windows to experiment with FP? I would prefer a JVM based approach, but another post on SO has indicated that a real FP language cannot be implemented on the JVM due to a lack of support for tail recursion. What say you?
EDIT: As I've said, I've experimented a fair bit with Haskell; on the advice of one of the answers I've been reviewing the Scala website. Looking over the Scala examples, the code seems more "familiar" (my background is C and Java), but it seems decidedly more OO/procedural and less functional. A huge advantage of Scala would be that it gives me another language tool to use side by side with Java and could become another arrow in my current professional quiver, as opposed to solely being a learning exercise. When I get further into Scala, will the functional aspects become more predominant, or will I tend to end up just writing OO code with some functional influence? In other words, will Haskell challenge my preconceptions harder and faster than Scala?
Check out F#. The CLR has a .tail instruction so you can write F# code with tail calls that don't cause a StackOverflow (the exception, not the web site). Here is an intro video about F# from PDC.
If you really want to learn how to think in a functional way, Haskell is definitely the right choice. Just about every other language out there lets you slip into an imperative style much too easily. Haskell will force you into a functional mindset. I found this indispensible when learning. (You may certainly be more disciplined than I am, of course, but why push your luck?)
When you're satisfied with what you've learned from Haskell (which will be a lot!), you're set to go out and evaluate more liberal functional languages like Clojure or Scala. Or you can stay with Haskell, whose library situation isn't actually all that bad, either. At that point, it's a question of circumstance and personal preference. But in order to make such a choice, having learned how to think in a “pure” functional way first is, I think, vital.
I recommend PLT Scheme and SICP. The language is so simple that you can get on to the important concepts very quickly.
No way is Scala going to bend your mind anywhere near as much as Haskell will. The main reason to choose Scala over Haskell when learning FP is to give yourself a more gentle introduction to the dangerous wilds of monads, functors and higher-order goodness. Scala is great if you're coming from an object-oriented background trying to transition that knowledge into functional-land. It's not so great if you want to just dive head-first into the deep end.
Given what you're asking, I would recommend GHC Haskell. Nothing is going to warp your head quite as much as that. :-) With that said though, I think you should still keep an eye on Scala. There are many aspects of the language which are positively unique, particularly its type system (structural+nominal subtyping == sweet). It's not going to hurt your head quite so much as Haskell, but it will give you an insight into some concepts you may not find anywhere else, particularly the so-called "typeful programming" methodology.
Oh, and to answer the second part of your question (FP vs OO in Scala), I tend to write my code in a functional style within an object-oriented framework. It's a bit difficult to describe, but that's the way it is. Think of it like designing an API from an object-oriented standpoint but implementing everything in a functional style. I keep things immutable and spend a lot of time using higher-order methods, but I do it all within the confines of inheritance and conventional nominal subtyping. Every so often, I'll still write something imperative, but only when it is cleaner to do so than to use the functional style.
Also look at Clojure.
In other words, will Haskell challenge my preconceptions harder and faster than Scala?
Yes.
If you really want to learn, get far outside your comfort zone.
Are you really going to use Scala for production code in the next 3 months, anyway?
Look at Scala. It targets the JVM, interoperates with Java, and has many state of the art functional programming features.
I love using Haskell and GHC. GHC includes an interactive interpreter (GHCI) and has wonderfully helpful error messages. Plus Haskell's one of the best examples of a truly functional language, and not too bad to use once you experiment with it a bit. Plus it has an awesome type system.
ever tried Prolog? ... that'll
?- bend(your_mind).
Yes
?- bend(X).
X = your_mind
It gave me a whole new perspective anyway ...
plenty info out there

What are the benefits of functional programming? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What do you think the benefits of functional programming are? And how do they apply to programmers today?
What are the greatest differences between functional programming and OOP?
The style of functional programming is to describe what you want, rather than how to get it. ie: instead of creating a for-loop with an iterator variable and marching through an array doing something to each cell, you'd say the equivalent of "this label refers to a version of this array where this function has been done on all the elements."
Functional programming moves more basic programming ideas into the compiler, ideas such as list comprehensions and caching.
The biggest benefit of Functional programming is brevity, because code can be more concise. A functional program doesn't create an iterator variable to be the center of a loop, so this and other kinds of overhead are eliminated from your code.
The other major benefit is concurrency, which is easier to do with functional programming because the compiler is taking care of most of the operations which used to require manually setting up state variables (like the iterator in a loop).
Some performance benefits can be seen in the context of a single-processor as well, depending on the way the program is written, because most functional languages and extensions support lazy evaluation. In Haskell you can say "this label represents an array containing all the even numbers". Such an array is infinitely large, but you can ask for the 100,000th element of that array at any moment without having to know--at array initialization time--just what the largest value is you're going to need. The value will be calculated only when you need it, and no further.
The biggest benefit is that it's not what you're used to. Pick a language like Scheme and learn to solve problems with it, and you'll become a better programmer in languages you already know. It's like learning a second human language. You assume that others are basically a variation on your own because you have nothing to compare it with. Exposure to others, particular ones that aren't related to what you already know, is instructive.
Why Functional Programming Matters
http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf
Abstract
As software becomes more and more complex, it is more and
more important to structure it well. Well-structured software is easy
to write and to debug, and provides a collection of modules that can
be reused to reduce future programming costs.
In this paper we show
that two features of functional languages in particular, higher-order
functions and lazy evaluation, can contribute significantly to
modularity. As examples, we manipulate lists and trees, program
several numerical algorithms, and implement the alpha-beta heuristic
(an algorithm from Artificial Intelligence used in game-playing
programs). We conclude that since modularity is the key to successful
programming, functional programming offers important advantages for
software development.
A good starting point therefore would be to try to understand some things that are not possible in imperative languages but possible in functional languages.
If you're talking about computability, there is of course nothing that is possible in functional but not imperative programming (or vice versa).
The point of different programming paradigms isn't to make things possible that weren't possible before, it's to make things easy that were hard before.
Functional programming aims to let you more easily write programs that are concise, bug-free and parallelizable.
I think the most practical example of the need for functional programming is concurrency - functional programs are naturally thread safe and given the rise of multi core hardware this is of uttermost importance.
Functional programming also increases the modularity - you can often see methods/functions in imperative that are far too long - you'll almost never see a function more than a couple of lines long. And since everything is decoupled - re-usability is much improved and unit testing is very very easy.
It doesn't have to be one or the other: using a language like C#3.0 allows you to mix the best elements of each. OO can be used for the large scale structure at class level and above, Functional style for the small scale structure at method level.
Using the Functional style allows code to be written that declares its intent clearly, without being mixed up with control flow statements, etc. Because of the principles like side-effect free programming, it is much easier to reason about code, and check its correctness.
Once the program grows, the number of commands in our vocabulary becomes too high, making it very difficult to use. This is where object-oriented programming makes our life easier, because it allows us to organize our commands in a better way.
We can associate all commands that involve customer with some customer entity (a class), which makes the description a lot clearer. However, the program is still a sequence of commands specifying how it should proceed.
Functional programming provides a completely different way of extending the vocabulary. Not limited to adding new primitive commands; we can also add new control structures–primitives that specify how we can put commands together to create a program. In imperative languages, we were able to compose commands in a sequence or using a limited number of built in constructs such as loops, but if you look at typical programs, you'll still see many recurring structures; common ways of combining commands
Do not think of functional programming in terms of a "need". Instead, think of it as another programming technique that will open up your mind just as OOP, templates, assembly language, etc may have completely changed your way of thinking when (if) you learned them. Ultimately, learning functional programming will make you a better programmer.
If you don't already know functional programming then learning it gives you more ways to solve problems.
FP is a simple generalization that promotes functions to first class values whereas OOP is for large-scale structuring of code. There is some overlap, however, where OOP design patterns can be represented directly and much more succinctly using first-class functions.
Many languages provide both FP and OOP, including OCaml, C# 3.0 and F#.
Cheers,
Jon Harrop.

Resources