What are the benefits of functional programming?

Rayne picture Rayne · Sep 24, 2008 · Viewed 51.6k times · Source

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?

Answer

Chris Wenham picture Chris Wenham · Sep 24, 2008

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.