Many people say that code writen in functional programming language is shorter than code writen in other programming paradigm languages.But why?
-
There are methods of abstraction in a functional language and of course often already implemented. OO languages has similar features like iterator and perhaps generators. I'm not certain that functional programming is shorter against a properly though out OO equivalent. (BTW: My favorite languages are LISPs) – Sylwester Aug 17 '15 at 14:20
1 Answers
One big reason is the greater use of higher-order functions. A simple example is map
. The following are equivalent:
# Procedural psuedocode
result = []
for value in other_list:
add somefunc(value) to result
# Functional pseudocode
let result = map(somefunc, other_list)
The higher-order function map
abstracts away the code that iterates over the first list and sequentially adds the function return value to the new list. Other higher-order functions can be used to implement other techniques that are commonly spelled out (whether by necessity or not) in more detail in other paradigms.
Another less commonly seen higher-order function is composition. In many languages, you write code like
def new_function(x):
return func2(func1(x))
value = new_function(5)
or
lambda x: func2(func1(x))
In a functional style, you would write (or have) a compose
function to handle the details, instead of having to write each composed function individually.
def compose(f, g):
def _(x):
return f(g(x))
value = compose(func2, func1)(x)
Some languages, like Haskell, even provide a composition operator:
value = (func2 . func1)(x)

- 497,756
- 71
- 530
- 681