🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Currying and Composition

Currying is the way Haskell functions take their inputs one at a time. This lesson also joins functions together with composition and the $ operator.

Giving one input makes a new function

add takes its two inputs one at a time. The binding add5 keeps the first input, 5, and waits for the second.

add x y = x + y
add5 = add 5

main :: IO ()
main = print (add5 7)

Composition runs the right function first

The expression (double . addOne) first adds 1 to 4. It then doubles that result.

double x = x * 2
addOne x = x + 1

main :: IO ()
main = print ((double . addOne) 4)

$ applies a function to the whole result

The $ operator makes print apply to the whole calculation after it. The program prints 10 + 5 as one value.

main :: IO ()
main = print $ 10 + 5

Example

add x y = x + y
add5 = add 5
double x = x * 2
addOne x = x + 1

main :: IO ()
main = print $ (double . addOne) (add5 3)

Key points

  • Currying: a Haskell function takes its inputs one at a time.
  • Partial application: giving a function only its first input produces a new function that waits for the rest.
  • add5: the binding add5 = add 5 is a function that adds 5 to its input.
  • Composition: the . operator joins two functions so the output of one becomes the input of the next.
  • Order in composition: in (f . g) x, g runs first and f runs on its result.
  • Dollar sign: the $ operator applies a function to the whole expression that follows it.

In this example, add5 first adds 5 to 3, giving 8. The composition then adds 1 to give 9 and doubles that to 18, and $ lets print take that whole result.

Note

partial application works because each function really takes one input and returns the next function.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

If add x y = x + y and add5 = add 5, what is add5 4?