Haskell Curry (and Uncurry)
When we write that a function F has type a → b → c, we can say two things about it.
- the function takes two parameters of type a and b and returns a type c. [i.e. (a → b) → c ]
- Or, the function takes a parameter of type a and returns a function of type b → c . [i.e. a → (b → c) ]
By default Haskell function types are curried, meaning the types are all right associative, i.e. its like option 2.( Although the function application itself is left associative, and is discussed in Haskell Higher Order function post.) This helps Haskell to support partial forms. If a function is called with fewer parameters than actually required then we get back a function (called partially applied function) that takes the rest of the parameters that were not provided while calling the initial function. If we call function F with a parameter of type a then we get back the partially applied function of type b → c.
add :: Int -> Int -> Int
add x y = x+yghci> let add2 = add 3
ghci> add2 4
7ghci> add 3 4
7
In the above example, when we call add function with only one parameter, 3, it returns a function (we named it add2). When that function is fed another parameter 4, we get back the result. We could have just fed the parameters together, but internally it would do the same thing.
Haskell has inbuilt curry and uncurry functions, to convert uncurried functions to curried functions, and vice versa.
curry :: ((a, b) -> c) -> a -> b -> c
uncurry :: (a -> b -> c) -> ((a, b) -> c)
Let us see an example of uncurrying a curried function.
cur1 :: (Num a) => a -> a -> a cur1 x y = x+yghci>add1 = uncurry cur1
ghci> add1 (1,2)
3
ghci> add1 1
**ERROR**
Now let's see the other way around
uncur1 :: (Num a) => (a,a) -> a
uncur1 x = fst x + snd xghci> add1 = curry uncur1
ghci> add1 1 2
3
ghci> let add2 = add1 1
ghci> add2 2
3