typestar

Guards and where in Haskell

Turns a term of exam scores into a letter grade with a note attached.

-- Guards pick a branch by Boolean test; otherwise is a synonym for True.
module ExamGrades where

grade :: [Int] -> String
grade scores
  | average >= 90 = "A" ++ note
  | average >= 80 = "B" ++ note
  | average >= 70 = "C" ++ note
  | otherwise     = "F" ++ note
  where
    -- One where block, shared by every guard in the equation above.
    average = sum scores `div` max 1 (length scores)
    best = maximum (0 : scores)
    note
      | average == best = " (steady all term)"
      | otherwise       = " (best was " ++ show best ++ ")"

How it works

  1. Each guard tests average against a cutoff and the last one is otherwise.
  2. The where block binds average and best once for all four guards.
  3. note is itself guarded, comparing average == best to choose its wording.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
504
Tokens
96
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 2 of 3 in Pattern matching, step 8 of 27 in Language basics.

← Previous Next →