typestar

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

  1. boxFee weightKg ratePerKg takes its two arguments written side by side.
  2. discountFor 0 is a separate equation from discountFor n and is tried first.
  3. totalCost calls both, and main prints totalCost 2.5 1.8 3.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Functions, step 4 of 27 in Language basics.

← Previous Next →

Defining functions in other languages