Currying & partial application in Haskell
A tip calculator that hands out half-applied functions instead of numbers.
-- Every function takes one argument and returns a function.
module Tipping where
addTip :: Double -> Double -> Double
addTip rate amount = amount * (1 + rate)
-- Supply only the rate and a Double -> Double is left waiting.
standardTip :: Double -> Double
standardTip = addTip 0.18
checks :: [Double]
checks = [12.0, 31.5, 8.25]
-- Partials go straight into map; (* 100) is an operator section.
withTips :: [Double]
withTips = map standardTip checks
inCents :: [Double]
inCents = map (* 100) (map (addTip 0.25) checks)
How it works
addTip rate amounttakes its arguments one at a time rather than as a pair.standardTip = addTip 0.18fixes the rate and leaves aDouble -> Doublebehind.map standardTip checksfeeds a partial to map, and(* 100)is an operator section.
Keywords and builtins used here
DoubleaddTipchecksinCentsmodulestandardTipwherewithTips
The run, in numbers
- Lines
- 19
- Characters to type
- 523
- Tokens
- 77
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 62 seconds.
Step 2 of 3 in Functions, step 5 of 27 in Language basics.