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
- Each guard tests
averageagainst a cutoff and the last one isotherwise. - The
whereblock bindsaverageandbestonce for all four guards. noteis itself guarded, comparingaverage == bestto choose its wording.
Keywords and builtins used here
IntStringgrademodulewhere
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.
Step 2 of 3 in Pattern matching, step 8 of 27 in Language basics.