How does currying work?

Viewed 12931

I'm very new to Haskell and FP in general. I've read many of the writings that describe what currying is, but I haven't found an explanation to how it actually works.

Here is a function: (+) :: a -> (a -> a) If I do (+) 4 7, the function takes 4 and returns a function that takes 7 and returns 11. But what happens to 4 ? What does that first function do with 4? What does (a -> a) do with 7?

Things get more confusing when I think about a more complicated function:

max' :: Int -> (Int -> Int)
max' m n | m > n = m
         | otherwise = n

what does (Int -> Int) compare its parameter to? It only takes one parameter, but it needs two to do m > n.

6 Answers

Haskell is based on Lambda calculus. Internally what happens is that everything gets converted into a function. So your compiler evaluates (+) as follows

(+) :: Num a => a -> a -> a
(+) x y = \x -> (\y -> x + y) 

That is, (+) :: a -> a -> a is essentially the same as (+) :: a -> (a -> a). Hope this helps.

Related