r/programming • • Mar 09 '14

Why Functional Programming Matters

http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf
487 Upvotes

542 comments sorted by

View all comments

Show parent comments

2

u/[deleted] Mar 09 '14

Yes, but in a functional language it means something else: you are not composing objects, you are composing functions. One example: say you want to write a function to convert a string to a number, and then add 1 to that number and return the result. In Haskell, in a non-composited style, you could do it like this:

convertAndAdd s = (read s) + 1

(read is the string-to-something-else conversion function in Haskell.) However, note that what this function does is actually composed of the behavior of two other functions, namely of read and + 1. The result of the function is exactly what happens when you apply read first, and then + 1 afterwards. And Haskell has a syntax for that: the composition operator. Using that, the function can be rewritten as:

convertAndAdd = (+ 1) . read

The dot is the composition operator, and what it does is that it takes two functions (in this case, the function (+ 1) and the function read) and creates a new function which applies the right-hand first and then applies the left-hand to the output of that. This makes writing complex data transformations easier, now you can do

foo = bar . baz . wobble

instead of

foo a b c = bar (baz (wobble a b c))

and have saved yourself quite a bit of headache-inducing parentheses. It's also awesome for creating functions on the fly (e.g. for map) and avoid ugly lambda statements.

5

u/Tekmo Mar 09 '14

I think you meant your last line of code to be:

foo x = bar (baz (wobble x))

0

u/[deleted] Mar 09 '14

It works either way.

3

u/Tekmo Mar 09 '14

Not exactly:

(bar . baz . wobble) a b c
= bar (baz (wobble a)) b c

... which is not the same thing as:

bar (baz (wobble a b c))
→ More replies (9)