Function Currying
All functions have a single parameter.
Functions of more than one parameter actually returns a new function.
No need to pass all parameters (partial application).
Example:
prod 3 5 is, in reality, (prod 3) 5
First we apply 3, and the result is a function that expects another integer.
prod :: Int -> Int -> Int
- Looks like a function taking two
Ints and returning anInt. - But under the hood it's actually:
prod :: Int -> (Int -> Int)
- Meaning:
prodtakes oneInt- and returns a new function that takes another
Intand finally returns anInt.
(prod 3) :: (Int -> Int)
- Calling
prodwith 3. Sinceprodtakes only one argument at a time, it returns a new function waiting for the secondInt. - So
(prod 3)is a function: "Hey, give me anInt, and Iβll multiply it by 3."
And when you finally call:
(prod 3) 5 :: Int -- 15
-
Youβre calling that new function with
5, so it returns3 * 5 = 15. -
It turns out every multi-argument function in Haskell is just a chain of single-argument functions returning functions until all args are consumed.
-
This allows you to partially apply functions easily. Like a βfunction factory.β