Lambdas & sections in Haskell
A lambda is a function with no name; a section is an operator with one operand already filled in.
module Lambdas where
-- a lambda is a function with no name: backslash, argument, arrow, body
withSurcharge :: [Int] -> [Int]
withSurcharge = map (\cents -> cents + 75)
-- a section fixes one operand: (* 2) doubles whatever it is handed
peakFares :: [Int] -> [Int]
peakFares = map (* 2)
-- but (10 -) subtracts its argument from ten; (- 10) is a negative
transfersLeft :: [Int] -> [Int]
transfersLeft = map (10 -)
-- flip swaps the first two arguments, so 60 lands on the right of div
hoursFromMinutes :: Int -> Int
hoursFromMinutes = flip div 60
-- once a body branches, a named helper reads better than a lambda
zoneFare :: Int -> Int
zoneFare zones = if zones <= 1 then 250 else 250 + 125 * (zones - 1)
How it works
map (\cents -> cents + 75)passes a lambda: backslash, argument, arrow, body.map (* 2)andmap (10 -)are sections, and(- 10)would read as a negative number rather than subtraction.hoursFromMinutes = flip div 60puts 60 on the right ofdiv, andzoneFarebranches, which is where a named helper beats a lambda.
Keywords and builtins used here
IntelsehoursFromMinutesifmodulepeakFaresthentransfersLeftwherewithSurchargezoneFare
The run, in numbers
- Lines
- 20
- Characters to type
- 709
- Tokens
- 94
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 81 seconds.
Step 3 of 3 in Higher-order, step 15 of 27 in Language basics.