Currying is the process of transforming a function that takes multiple arguments into a function that takes just a single argument and returns another function if any arguments are still needed.
f :: a -> b -> c
is the curried form of
g :: (a, b) -> c
You can convert these two types in either directions with the Prelude functions
f = curry g g = uncurry f
Both forms are equally expressive. It holds
f x y = g (x,y) ,
however the curried form is usually more convenient because it allows partial application.
In Haskell, all functions are considered curried: That is, all functions in Haskell take just single arguments.This is mostly hidden in notation, and so may not be apparent to a new Haskeller. Let's take the function
div :: Int -> Int -> Int
div 11 2unsurprisingly evaluates to
5. But there's more that's going on than immediately meets the untrained eye. It's a two-part process. First,
Int -> Int
2, and yields
You'll notice that the notation for types reflects this: you can read
Int -> Int -> Int
Ints and returns an
Int", but what it's really saying is "takes an
Intand returns something of the type
Int -> Int--that is, it returns a function that takes an
Intand returns an
Int. (One can write the type as
Int x Int -> Intif you really mean the former--but since all functions in Haskell are curried, that's not legal Haskell. Alternatively, using tuples, you can write
(Int, Int) -> Int, but keep in mind that the tuple constructor
(,)itself can be curried.)
Much of the time, currying can be ignored by the new programmer. The major advantage of considering all functions as curried is theoretical: formal proofs are easier when all functions are treated uniformly (one argument in, one result out). Having said that, there are Haskell idioms and techniques for which you need to understand currying.
- partial application
- Section of an infix operator
- Sometimes it's valuable to think about functions abstractly without specifically giving all their arguments: this is the Pointfree style.
- Sometimes half the work of the function can be done looking only at the first argument (but there really is only one argument, remember?): see functional dispatch.
- Write the function
\(x,y) -> (y,x)without lambda and with only Prelude functions