Defining functions in Haskell
A shipping quote assembled from two small functions and a literal pattern.
-- A function is an equation: name, arguments by juxtaposition, body.
boxFee :: Double -> Double -> Double
boxFee weightKg ratePerKg = 3.5 + weightKg * ratePerKg
-- Two clauses tried top to bottom: the literal 0 first, then any n.
discountFor :: Int -> Double
discountFor 0 = 0.0
discountFor n = min 0.25 (fromIntegral n * 0.05)
totalCost :: Double -> Double -> Int -> Double
totalCost weightKg ratePerKg boxes =
boxFee weightKg ratePerKg * (1 - discountFor boxes)
main :: IO ()
main = print (totalCost 2.5 1.8 3)
How it works
boxFee weightKg ratePerKgtakes its two arguments written side by side.discountFor 0is a separate equation fromdiscountFor nand is tried first.totalCostcalls both, andmainprintstotalCost 2.5 1.8 3.
Keywords and builtins used here
DoubleIOIntboxFeediscountFormaintotalCost
The run, in numbers
- Lines
- 15
- Characters to type
- 516
- Tokens
- 75
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 56 seconds.
Step 1 of 3 in Functions, step 4 of 27 in Language basics.