Hacker News new | past | comments | ask | show | jobs | submit login

Not a very good intro to functional programming or currying mostly because it never explains WHY you would ever want to use currying.



The answer is that currying reduces the cost of breaking apart and combining functions on their arguments, two things that are done frequently in functional programming.

Currying allows functions to be broken apart ("specialized") on certain arguments for virtually free because specialization and normal function application, in effect, become the same thing.

Consider Haskell's _map_ function for example:

    map :: (a -> b) -> [a] -> b
You can specialize it into a function that adds one to every element in a list by simply applying it to its first argument:

    incList = map (+1)
Currying also reduces the cost of combining functions by allowing any function that returns a function to have the returned function applied to any following arguments directly, without need of intervening syntax. For example, _flip_ modifies a function of two arguments (or more, thanks to currying) to receive its first two arguments in "flipped" order, the second first and the first second:

    flip :: (a -> b -> c) -> (b -> a -> c)
To flip _map_'s arguments, I don't need to write

    let flipMap = flip map in flipMap [1,2,3] (+1)
but, thanks to currying, can simply write

    flip map [1,2,3] (+1)
The value of these tools, however, is not to be able to write complete calls like those in my examples above but to quickly assemble from simple functions the exact functions needed to solve the problems at hand, usually by feeding those functions into the higher-order functions found in libraries.

In sum, currying makes some of the most frequently done things in functional programming virtually free.


Currying is like air in functional programming.

Here's a small example:

map (+ 3) [1, 2, 3] == [4, 5, 6]




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: