F#, lesson 4
Programs need to act differently depending on their data: charge children less, warn when a
value is too high. F# gives you two tools: if and match.
if is an expressionIn F#, if ... then ... else ... produces a value, so you can bind its result directly:
Since the whole if is one value, both branches must have the same type. if ok then "yes" else 0 does not compile.
Chain conditions with elif, and indent multi-line branches:
An if without else is allowed only when the branch returns (nothing), for example a
.
2 exercises to try what you just read.
unitprintfn| Operator | Meaning |
|---|---|
= | equal |
<> | not equal |
< > | less / greater than |
<= >= | less / greater or equal |
Note that equality is a single = and "not equal" is <>, not !=. Comparisons work on numbers,
strings, characters, lists and more, as long as both sides have the same type.
Combine conditions with && (and), || (or) and not:
&& and || stop early: if the left side already decides the answer, the right side is not
evaluated.
matchWhen you check one value against several cases, match is clearer than a ladder of elifs:
The cases are tried from top to bottom; the first one that fits wins. _ is the wildcard, which
matches anything. 6 | 7 matches either value. If your cases do not cover every possibility, the
compiler warns you, which catches many bugs before the program ever runs.
Add a condition to a case with when:
t is a new name for the value being matched, and the when guard decides whether the case
applies. Reach for if for a simple yes/no question, and match when there are several cases or
ranges.
A cinema charges by age: children under 13 pay 5, people aged 65 or older pay 7, and everyone else pays 12. Read an age (a whole number, 0 or more) and print the price.
Sample 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. Read a year and print leap or common.
Sample input:
Sample output:
let temp = int (stdin.ReadLine())
let advice = if temp > 25 then "Wear a hat" else "Bring a jacket"
printfn "%s" advicelet size =
if n < 10 then "small"
elif n < 100 then "medium"
else "large"let canRide = age >= 8 && height >= 120
let weekend = day = "Sat" || day = "Sun"
let weekday = not weekendlet dayName n =
match n with
| 1 -> "Monday"
| 2 -> "Tuesday"
| 6 | 7 -> "Weekend"
| _ -> "Another day"let describe temp =
match temp with
| t when t < 0 -> "freezing"
| t when t < 20 -> "mild"
| _ -> "warm"70Price: 72024leap