Haskell, lesson 4
Programs need to choose: charge shipping only on small orders, warn when a battery is low. In Haskell a decision is not a statement that runs one block or another. It is an expression that produces one value or another.
This defines a small function fee that takes the order total and returns the fee. (You will
learn functions properly in lesson 6; for now, read fee total = ... as "the fee for a total
is ...".)
Because if must always produce a value, the else is required, and both branches must
have the same type. You can use if anywhere a value fits, including inside main:
2 exercises to try what you just read.
| Operator | Meaning |
|---|
== | equal |
/= | not equal (note: not !=) |
< <= > >= | ordering |
&& | and |
|| | or |
not | a function that flips a Bool: not isOpen |
&& and || are lazy: if the left side decides the answer, the right side is never
evaluated.
When there are more than two cases, nested ifs get messy. Guards are the idiomatic
alternative. Each line starts with |, then a condition, then = and the result. Haskell
tries them from top to bottom and uses the first one that is True:
otherwise is simply another name for True, so it catches everything left over. Always end
with it, or a value that matches no guard will crash the program.
case compares a value against patterns, which are shapes the value can have. A literal
matches exactly; _ matches anything:
You can also match patterns directly in the function definition, one equation per case. This is very common in Haskell:
The equations are tried in order, so put the specific cases first and the catch-all last.
A good Haskell habit: put the decision in a pure function (no IO), and keep main small.
main reads the input, calls the function, and prints the result. Pure functions are easier
to test and reason about because they always give the same output for the same input.
Write describe :: Int -> String with guards, then use it in main. Read a whole-number
temperature in Celsius and print one word:
freezingcoldmildhotSample input:
Sample output:
A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap
years only if they are also divisible by 400. Write isLeap :: Int -> Bool, read a year, and
print either <year> is a leap year or <year> is not a leap year.
Sample input:
Sample output:
fee :: Int -> Int
fee total = if total >= 50 then 0 else 5main :: IO ()
main = do
battery <- readLn :: IO Int
putStrLn (if battery < 20 then "Low battery!" else "Battery OK")grade :: Int -> String
grade score
| score >= 90 = "A"
| score >= 80 = "B"
| score >= 70 = "C"
| otherwise = "keep practising"dayType :: String -> String
dayType day = case day of
"Sat" -> "weekend"
"Sun" -> "weekend"
_ -> "weekday"describe :: Int -> String
describe 0 = "none"
describe 1 = "one"
describe _ = "many"18mild20242024 is a leap year