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.
Related
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've noticed that there are certain core concepts that a lot of functional programming fanatics cling to:
Avoiding state
Avoiding mutable data
Minimizing side effects
etc...
I'm not just wondering what other things make functional programming, but why these core ideas are good? Why is it good to avoid state, and the rest?
The simple answer is that if you don't have extra state to worry about, your code is simpler to reason about. Simpler code is easier to maintain. You don't need to worry about things outside a particular piece of code (like a function) to modify it. This has really useful ramifications for things like testing. If your code does not depend on some state, it becomes much easier to create automated tests for that code, since you do not need to worry about initializing some state.
Having stateless code makes it simpler to create threaded programs as well, since you don't need to worry about two threads of execution modifying/reading a shared piece of data at the same time. Your threads can run independent code, and this can save loads of development time.
Essentially, avoiding state creates simpler programs. In a way, there's less "moving parts" (i.e., ways lines of code can interact), so this will generally mean that the code is more reliable and contains less faults. Basically, the simpler the code, the less can go wrong. To me this is the essence of writing state-less code.
There are plenty of other reasons to create stateless, "functional" code, but they all boil down to simplicity for me.
In addition to what #Oleksi said, there is another important thing: referential transparency and transactional data structures. Of course, you do not need a functional programming language to do so, but it's a bit easier with them.
Purely functional data structures are guaranteed to remain the same - if one function returned a tree, it will always be the same tree, and all the further transforms would create new copies of it. It's much easier to backtrack to any previous version of a data structure this way, which is important for many essential algorithms.
Very generally, functional programming means:
encouraging the use of (first-class) functions
discouraging the use of (mutable) state
Why is mutation a problem? Think about it: mutation is to data structures what goto is to control flow. I.e., it allows you to arbitrarily "jump" to something completely different in a rather unstructured manner. Consequently, it is occasionally useful, but most of the time rather harmful to readability, testability, and compositionality.
One typical functional feature is "no subtyping". While it sounds a little bit odd to call this a feature, it is, for two (somehow related) reasons:
Subtyping relationships lead to a bunch of not-so-obvious problems. If you don't limit yourself to single or mixin inheritance, you end up with the diamond problem. More important is that you have to deal with variance (covariance, contravariance, invariance), which quickly becomes a nightmare, especially for type parameters (a.k.a. generics). There are several more reasons, and even in OO languages you hear statements like "prefer composition over inheritance".
On the other hand, if you simply leave out subtyping, you can reason much more detailled about your type system, which leads to the possibility to have (almost) full type inference, usually implemented using extensions of Hindley Milner type inference.
Of course sometimes you'll miss subtyping, but languages like Haskell have found a good answer to that problem: Type classes, which allow to define a kind of common "interface" (or "set of common operations") for several otherwise unrelated types. The difference to OO languages is that type classes can be defined "afterwards", without touching the original type definitions. It turns out that you can do almost everything with type classes that you can do with subtyping, but in a much more flexible way (and without preventing type inference). That's why other languages start to employ similar mechnisms (e.g. implicit conversions in Scala or extension methods in C# and Java 8)
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.
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
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?
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.