Cogs and Levers A blog full of technical stuff

Function currying in Haskell

I think it’s important to follow up my previous post on anonymous functions with a post on currying. One of the more difficult concepts to think about (only because Haskell does a great job of separating you from this) is that every function only has 1 argument.

Take this basic greeting example which expects the name of someone who is doing the greeting and the name of someone who is being greeted:

let sayHello toWho fromWho = fromWho ++ " says Hello to " ++ toWho

This is a pretty trivial example. Give it two names and the computer will appear to play nice between these two people:

*Main> sayHello "John" "Peter"
"Peter says Hello to John"

We like John so much, that we’re going to make a new function using this existing one.

let sayHelloToJohn = sayHello "John"

So now, we can get anyone to play nice with John:

*Main> sayHelloToJohn "Peter"
"Peter says Hello to John"
*Main> sayHelloToJohn "Joe"
"Joe says Hello to John"
*Main> sayHelloToJohn "Jane"
"Jane says Hello to John"

Great! We’ve just made a partially applied function. When you don’t specify enough parameters to a function, you’re actually returned a function (or, partially applied function) that you can continue to use. Breaking down how this works, when Jane is saying hello to John she is actually doing so by doing this:

(sayHello "John") "Jane"

This should at least explain my outlandish claims above of functions only having one argument, anyway. You’ve just witnessed function currying in motion. These principles are also directly applicable on infix functions as well, they just need a little extra help to be told so. Take this for example:

double :: (Floating a) => a -> a
double = (*2)

Ignoring the function definition, you can see that all you need to do for infix functions is to surround then with parenthesis. You need to supply the value that makes it a partial application of course!