Currying is a technique to convert a function with multiple arguments to many functions with only one argument called in sequence. I will use python this time to demonstrate currying.
def unCurriedAdd(l, r):
return l + r
def curriedAdd(l):
def inner(r):
return l + r
return inner
unCurriedAdd(10, 15)
curriedAdd(10)(15)
curriedAdd and inner has only one argument. The result of calling curriedAdd is a function (inner) that takes a single argument and finishes the calculation. Every function that takes multiple arguments can be translated this way to functions with a single argument.
Let's have a look at the type signature of the * operator.
(*) :: Int -> Int -> Int
(*) :: Int -> (Int -> Int)
The two type declarations above are equivalent because arrow associates to the right. Adding some parentheses changes our understanding of this function. We see a function taking a single Int parameter and returning a function. The returned function takes a single Int parameter and returns an Int.
Haskell functions are curried by default. That is why the arguments are separated by the same operator than the arguments and the return value. Calling a function with only one parameter will return a function that expects the rest of the parameters. This is called partial application.
(*) :: Int -> Int -> Int
tenTimes :: Int -> Int
tenTimes = (*) 10
tenTimesFifteen :: Int
tenTimesFifteen = tenTimes 15
- Implement a function that concatenates two strings.
concatenate :: String -> String -> String
- Implement a function that given a name, returns the "hello name" String. Use the concatenate function from the previous exercise.
greet :: String -> String
Infix operators need to be put between parentheses if they are not used in an infix position.
2 ^ 10 == (^) 2 10
2 ^ 10 == (2^) 10
2 ^ 10 == (^10) 2
Any binary function can be used in an infix position by putting the function name between backticks.
mod 10 3 == 10 `mod` 3
- Implement the greets function.
"Luke" `greets` "Leia" == "Luke: Hello Leia!"