Home / Learn / 3 Text and conditions
3.4 Choosing between two values: if
Page 5 of 10
3.4.1 What if is
if chooses between two values by a condition. Think of a sign at the till: "orders of 100.00 or more ship free; otherwise shipping is 4.90". The clerk checks one fact, and the answer is one of two prices. if writes that rule: if goods >= 10_000 then 0 else 490.
Two words name its parts:
- the condition, after
if: aBool; - the branches: the value after
then, which is the answer when the condition istrue, and the value afterelse, which is the answer when it isfalse.
Only the branch the condition picks is worked out. The other is skipped. An if is an expression: a piece of code that gives a value, as 2 + 3 or a call does. So an if can stand wherever a value goes: as the body of a function, after let, as an argument, or as part of a larger expression.
3.4.2 Why a program chooses
A function without a choice answers every input the same way. Here is a product page that says how many units are left, with one sentence for every case:
module shelf
--- What a product page says about the stock of a product: one sentence for every case.
availability(on_hand: Int) -> Text = "only {on_hand} units left"
--- Prints what the product page says for four stock levels.
pub main() -> Unit
uses @console: Console[print]
=
@console.print(availability(0))
@console.print(availability(1))
@console.print(availability(3))
@console.print(availability(40))only 0 units left
only 1 units left
only 3 units left
only 40 units leftOnly one line in four reads well. "only 0 units left" should say that the product is out of stock, "only 1 units left" is bad English, and "only 40 units left" makes a full shelf sound scarce. The right sentence depends on the number, and a single text cannot say so. if can.
3.4.3 How to write if
The module choices has an if in each place it can stand, and main prints one line for each:
module choices
--- Whether a parcel counts as heavy: an `if` as a function's whole body.
weight_class(grams: Int) -> Text = if grams > 2_000 then "heavy" else "light"
--- The name of a shipping zone: an `else if` chain.
zone_name(zone: Int) -> Text = if zone == 1 then "home" else if zone == 2 then "neighbors" else "world"
--- The handling fee of an order: an `if` in parentheses, as one part of a sum.
handling(goods: Int) -> Int = 190 + (if goods >= 10_000 then 0 else 300)
--- The box a parcel needs: an `if` over several lines, with a block in each branch.
box_for(grams: Int) -> Text
=
if grams <= 1_000
"small box"
else if grams <= 5_000
let kilos = (grams + 999) / 1_000
"medium box for {kilos} kg"
else
"large box"
--- Prints one line for each place an `if` can stand.
pub main() -> Unit
uses @console: Console[print]
=
@console.print("{weight_class(2_300)}, {weight_class(800)}")
@console.print("{zone_name(1)}, {zone_name(2)}, {zone_name(7)}")
@console.print("{handling(4_500)}, {handling(12_000)}")
@console.print("{box_for(800)}; {box_for(3_200)}; {box_for(9_000)}")
let units = 1
let word = if units == 1 then "unit" else "units"
@console.print("{units} {word}")
@console.print(if units > 10 then "a bulk order" else "a regular order")heavy, light
home, neighbors, world
490, 190
small box; medium box for 4 kg; large box
1 unit
a regular order3.4.3.1 if … then … else …
if grams > 2_000 then "heavy" else "light" is the whole form: the keyword if, the condition, then and the value for true, else and the value for false, all on one line. 2300 grams is above 2000, so weight_class(2_300) is "heavy"; 800 is not, so weight_class(800) is "light".
3.4.3.2 More than two cases: else if
The value after else may be another if. if zone == 1 then "home" else if zone == 2 then "neighbors" else "world" tries the conditions in order, and the first that holds gives the value. The last else takes every case that no condition took, here every zone but 1 and 2.
3.4.3.3 As part of a larger expression: in parentheses
190 + (if goods >= 10_000 then 0 else 300) adds the result of the if to 190. The parentheses are required when an if is one part of a larger expression, so that the reader and the checker see where it ends. An order of 4500 cents pays 190 plus 300, and one of 12000 cents pays 190 plus 0.
3.4.3.4 After let, and as an argument
let word = if units == 1 then "unit" else "units" names the value an if gives. @console.print(if units > 10 then "a bulk order" else "a regular order") passes it to a call. In both places the if is the whole value, so it needs no parentheses.
3.4.3.5 Over several lines: a block in each branch
When a branch needs a step of its own before its value, write the if over several lines. box_for chooses a box by weight:
--- The box a parcel needs: an `if` over several lines, with a block in each branch.
box_for(grams: Int) -> Text
=
if grams <= 1_000
"small box"
else if grams <= 5_000
let kilos = (grams + 999) / 1_000
"medium box for {kilos} kg"
else
"large box"The form has four rules:
- The condition goes on the
ifline, with nothen.if grams <= 1_000ends the line. - Each branch is indented two spaces under its
if,else iforelse, which each stand on a line of their own. - A branch may hold several lines, a block. Its lines run in order, from the top, and its value is its last line: the lines before it are steps, such as a
let. The middle branch nameskiloswithlet, then gives the text. A function's body of several lines works the same way, as section 6.2 shows in full. - The whole
ifstill gives one value, so it still has itselse, and every branch gives the same type.
A then at the end of the if line, against rule 1, is U0101:
[U0101] Error: unexpected end of line, expected an expressionRemove the then, so that the condition ends the line. The diagnostic's repair makes the same edit, and una fix . applies it.
Leave out the last else, against rule 4, and the check reports U0101 where the if ends, at the next declaration:
[U0101] Error: unexpected end of block, expected `else`main prints the box for 800, 3200 and 9000 grams:
small box; medium box for 4 kg; large box3200 grams is above 1000 and not above 5000, so the middle branch runs: it rounds the weight up to 4 started kilograms. / drops the fraction (section 2.2), so adding 999 grams before dividing counts every started kilogram: 3200 plus 999 is 4199, and 4199 / 1000 is 4. Use this form when a branch needs a let or would make one line hard to read. Both forms are canonical: una fmt . keeps whichever one you wrote.
Una has one more form of if, over several lines and with no else, which runs its lines only when the condition holds, and when, which chooses by the shape of a value. Chapter 8 covers every form of if, and section 4.3 introduces when.
3.4.4 How if behaves
3.4.4.1 Every if on one line has its else
An if gives a value, so it needs one for each answer of its condition. Leave out the else:
[U0101] Error: unexpected end of line, expected `else`
╭─[ src/choices.una:4:65 ]
│
4 │ weight_class(grams: Int) -> Text = if grams > 2_000 then "heavy"
│ ┬
│ ╰── unexpected end of line, expected `else`
│
│ Help: repair 1: an `if` with `then` needs `else`; to fail early, make the rest of the body its `else` branch, as in `if x < 0 then fail Broke else x`, or use the block form, whose `else` block holds the restThe marks point at the end of the line, where una check expected else. Without it, weight_class(800) would have no text to give back. The Help line also mentions fail, which comes in chapter 7, and the block form of Over several lines; for an if on one line, the repair is the missing else and its value.
3.4.4.2 Parentheses around an if inside a larger expression
Without its parentheses, the if in handling does not check:
[U0101] Error: unexpected keyword `if`, expected an expression
╭─[ src/choices.una:10:37 ]
│
10 │ handling(goods: Int) -> Int = 190 + if goods >= 10_000 then 0 else 300
│ ─┬
│ ╰── unexpected keyword `if`, expected an expressionAfter 190 +, the checker expected a value, and an if may only start one in parentheses.
3.4.4.3 Both branches give the same type
The two branches are two possible values of one expression, so they must have one type. A branch that gives a number where the other gives a text is refused:
[U2001] Error: expected `Text`, found `Int`
╭─[ src/choices.una:20:45 ]
│
20 │ let word = if units == 1 then "unit" else 2
│ ┬
│ ╰── expected `Text`, found `Int`The then branch is a Text, so the checker expects a Text from the else branch too, and reports the Int it found there. A choice between "unit" and "units" is a choice between two texts.
3.4.4.4 The condition is a Bool
The condition of an if follows the rule of section 3.3: an Int or a Text is not a condition. if percent then … is U2001, as A number as a condition shows.
3.4.4.5 Only the chosen branch runs, and it knows why
The branch that the condition does not pick is never worked out. And inside the branch it picks, the checker knows that the condition holds, as it knew the left side of and in section 3.3. So an if can guard a step that would not be safe for every value:
--- The price of one unit of a pack, in cents, rounded down. An empty pack gives 0.
per_unit(cents: Int, units: Int) -> Int = if units > 0 then cents / units else 0150, 333, 0In the then branch, units > 0 holds, so the division by units is proved safe. For an empty pack, the else branch gives 0, and the division never runs.
This repairs the cut of section 3.2. fit_name cuts a name only when it is longer than 24 characters, and gives the name itself otherwise:
--- a/src/labels.una
+++ b/src/labels.una
@@ -1,7 +1,7 @@
module labels
--- A product name cut to the 24 characters a label has room for.
-pub fit_name(name: Text) -> Text = name.slice(start: 0, end: 24)
+pub fit_name(name: Text) -> Text = if name.len > 24 then name.slice(start: 0, end: 24) else name
--- Prints two names as a label shows them.
pub main() -> Unit[Desk lamp, brass]
[Wool rug, 120 by 180 cm,]In the then branch, name.len > 24, so 24 <= name.len holds and the cut is proved. A short name never reaches the cut. Section 8.3 shows what else a branch proves.
3.4.5 Stock messages with if
Back to the product page. The module stock gives each stock level its own sentence:
module stock
--- "unit" or "units", whichever goes with `count`.
pub units_word(count: Int) -> Text = if count == 1 then "unit" else "units"
--- What a product page says about the stock of a product.
pub availability(on_hand: Int) -> Text
=
let few = "only {on_hand} {units_word(on_hand)} left"
if on_hand <= 0 then "out of stock" else if on_hand < 5 then few else "in stock"
--- Prints what the product page says for four stock levels.
pub main() -> Unit
uses @console: Console[print]
=
@console.print(availability(0))
@console.print(availability(1))
@console.print(availability(3))
@console.print(availability(40))if count == 1 then "unit" else "units". The one-line form as a function's whole body: the word that goes with a count.let few = "only {on_hand} {units_word(on_hand)} left". The long form of a function may name values withletbefore its last line, and the last line is the function's result (section 6.2). Naming the sentence keeps theifshort.if on_hand <= 0 then "out of stock" else if on_hand < 5 then few else "in stock". Three cases, tried in order: an empty shelf, then a shelf with a few units, then every other.
una run . prints:
out of stock
only 1 unit left
only 3 units left
in stockEach stock level now gets the sentence that fits it, and the rule for each case is written once, where a reader looks for it.
3.4.6 When to use if
Which to use:
| You want to… | Use |
|---|---|
| Pick one of two values by a condition | if … then … else … |
| Pick one of several values, tried in order | else if, with a last else for the rest |
| Use the choice inside a sum or a comparison | the if in parentheses |
| Make a step safe that needs a condition, such as a cut or a division | an if whose then branch holds the step |
| Answer a yes-or-no question, not choose a value | a Bool expression, without if: write units > 0, not if units > 0 then true else false |
| Choose by the variant of a kind | when (section 4.3) |
3.4.7 Check yourself: if
wrap_fee prices gift wrapping:
--- The gift-wrapping fee of an order: nothing without a gift, 150 cents a unit, 500 at most.
wrap_fee(units: Int, gift: Bool) -> Int = if not gift then 0 else if units > 3 then 500 else 150 * unitsmain prints wrap_fee(2, gift: true), wrap_fee(5, gift: true) and wrap_fee(5, gift: false), separated by commas. Predict the line.
Show the answer
300, 500, 02 units as a gift take the last branch, 150 × 2 = 300. 5 units as a gift pass the second condition, units > 3, and pay the most, 500. Without a gift, the first condition, not gift, holds, and the other branches are never worked out.