Home / Learn / 9 Repeating: for

Release v0.4.0Edition 0.2

9.2 Names that change: let edit

Page 3 of 9

9.2.1 What an editable name is

A plain let gives a value a name for good (section 2.1): like a price printed on a tag, it says the same thing every time you read it. Some values must change as a program runs. Think of the display of a till: it shows a total, and each scanned item changes what it shows. The display is one thing, with one name, whose value moves.

An editable name is such a name. You declare it with let edit, and an assignment, a line of the form name = value, gives it a new value. Every later line that reads the name sees the new value.

9.2.2 Why some names must change

Without editable names, a running total needs a new name for each step:

src/till.unacheckrununa
module till

--- Prints the total of a till after each of three scans, with a new name for each total.
pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = 1_990
  let rug = 4_500
  let after_one = lamp
  let after_two = after_one + lamp
  let after_three = after_two + rug
  @console.print("after one item: {after_one} cents")
  @console.print("after two items: {after_two} cents")
  @console.print("after three items: {after_three} cents")
Output
after one item: 1990 cents
after two items: 3980 cents
after three items: 8480 cents

It works for three scans, written out one by one. In a loop it cannot work at all: the body is written once, so it cannot make a new name for each turn. A loop must carry its total from one turn to the next in the same name. Try it with a plain let:

src/demand.unauna
--- The units customers ask for over `weeks` weeks, at `per_week` units a week.
pub demand(weeks: Int, per_week: Int) -> Int
=
  let total = 0
  for week in 1..weeks
    total = total + per_week
  total

una check . reports:

Diagnostic
[U2019] Error: `total` is not editable; declare it `let edit total`, or the parameter `edit total`
   ╭─[ src/demand.una:8:5 ]
   │
 8 │     total = total + per_week
   │     ──┬──
   │       ╰──── `total` is not editable; declare it `let edit total`, or the parameter `edit total`
   │
   │ Note: run `una explain U2019` for an explanation
───╯

The marks point at total on the left of the assignment. A name declared with plain let is not editable, and the message names the declaration to write instead: let edit total. (The message also names an edit parameter, a parameter that a function may change for its caller, which section 16.2 covers.)

9.2.3 How to write let edit and an assignment

A till adds up the items a cashier scans:

src/till.unacheckrununa
module till

--- Prints the running total of a till as three items are scanned.
pub main() -> Unit
  uses @console: Console[print]
=
  let lamp = 1_990
  let edit total = 0
  let edit items = 0
  total = total + lamp
  items = items + 1
  total = total + lamp
  items = items + 1
  @console.print("{items} items, {total} cents")
  total = total + 4_500
  items = items + 1
  @console.print("{items} items, {total} cents")
  let edit receipt: Text = "LAMP-01"
  receipt = "{receipt}, LAMP-01, RUG-07"
  @console.print(receipt)
  1. let lamp = 1_990. A plain name. Its type, Int, comes from its value, and its value never changes.
  2. let edit total = 0. An editable name. Its first value is 0, and its type is the type of that value, Int.
  3. total = total + lamp. An assignment: the name on the left, =, and the new value on the right. The right side is worked out first, from the old value of total, and then total holds the result. An assignment is a statement, on a line of its own.
  4. let edit receipt: Text = "LAMP-01". A type written after the name, with :, as for a plain let. It is optional here, but it tells a reader what the name will hold.
  5. receipt = "{receipt}, LAMP-01, RUG-07". A text built from the old value: the way to add to the end of a text.

una run . prints:

Output
2 items, 3980 cents
3 items, 8480 cents
LAMP-01, LAMP-01, RUG-07

Read = in an assignment as "becomes", not as "is equal to": total = total + lamp says "the total becomes the old total plus the lamp". The comparison "is equal to" is == (section 3.3).

An assignment may also change one field of an editable record (section 4.1): restocked.units = restocked.units + per_delivery gives the record a new units and keeps its other fields. A record that changes shows it in a loop.

9.2.4 Accumulators: what a loop carries from turn to turn

An editable name that a loop builds up turn by turn is an accumulator. It is declared before the loop, with the value it should have when the loop takes no turn, and each turn updates it. After the loop, it holds the result. The step for this part has one function per kind of accumulator:

9.2.4.1 A sum

steps/14-accumulators/src/counts.unauna
--- The units customers ask for over `weeks` weeks, at `per_week` units a week: a sum.
pub demand(weeks: Int, per_week: Int) -> Int
=
  let edit total = 0
  for week in 1..weeks
    total = total + per_week
  total
Output
demand over 4 weeks: 20
demand over 0 weeks: 0

Before the loop, total is 0. Each of the 4 turns adds 5, so total goes 5, 10, 15, 20, and the last line of the function, total, gives that last value back. With 0 weeks, the range 1..0 is empty, no turn runs, and total keeps its first value, 0: the right answer, with no special case.

9.2.4.2 A count

steps/14-accumulators/src/counts.unauna
--- How many dashes a SKU holds: a count.
pub dashes_in(sku: Text) -> Int
=
  let edit count = 0
  for character in sku.chars()
    if character == "-"
      count = count + 1
  count
Output
dashes in LAMP-01-BR: 2

The count goes up only on the turns where the if holds: the two dashes of LAMP-01-BR.

9.2.4.3 A text that grows

steps/14-accumulators/src/counts.unauna
--- A SKU with a space after each character, for a sign that is read from afar: a text that
--- grows.
pub spaced(sku: Text) -> Text
=
  let edit sign = ""
  for character in sku.chars()
    sign = "{sign}{character} "
  sign.trim
Output
sign: [R U G - 0 7]

Each turn adds one character and a space to the end of sign. The last turn leaves a space at the end, which trim removes before the function gives the text back.

9.2.4.4 A flag

steps/14-accumulators/src/counts.unauna
--- Whether a SKU holds a digit: a flag that a turn may set.
pub has_digit(sku: Text) -> Bool
=
  let edit found = false
  for character in sku.chars()
    if character.is_digits()
      found = true
  found
Output
a digit in RUG-07: true, in GIFTCARD: false

A flag is a Bool that starts false and that a turn sets to true when it sees what it looks for. is_digits, from the prelude, is true when every character of a text is a digit from 0 to 9. Once the flag is true, the later turns leave it so. The loop still visits every character, since every turn runs.

9.2.4.5 A record that changes

steps/14-accumulators/src/counts.unauna
--- A shelf after `weeks` deliveries of `per_delivery` units: one field of a record changes.
pub after_deliveries(shelf: Shelf, weeks: Int, per_delivery: Int) -> Shelf
=
  let edit restocked = shelf
  for week in 1..weeks
    restocked.units = restocked.units + per_delivery
  restocked
Output
aisle 3: 16 units

let edit restocked = shelf makes an editable copy of the parameter. Each turn changes its field units, and its aisle stays 3. The caller's shelf does not change: the function changes its own copy and gives it back.

9.2.5 How editable names behave

9.2.5.1 A name lives to the end of its block

A block is a run of lines at the same indentation, such as the body of a function or of a loop. A name exists from its let line to the end of its block, and a line before the let cannot use it. This is why an accumulator is declared before its loop: a name declared inside the body would end with each turn.

9.2.5.2 One name, one meaning: no shadowing

Making a name that another let of the same body already made is an error, even with let both times:

src/till.unadiff
--- a/src/till.una
+++ b/src/till.una
@@ -7,2 +7,3 @@
   let lamp = 1_990
+  let lamp = 2_490
   let edit total = 0
Diagnostic
[U1002] Error: `lamp` is already bound in this scope; a local cannot rebind another
   ╭─[ src/till.una:8:7 ]
   │
 7 │   let lamp = 1_990
   │       ──┬─
   │         ╰─── first defined here
 8 │   let lamp = 2_490
   │       ──┬─
   │         ╰─── `lamp` is already bound in this scope; a local cannot rebind another
   │
   │ Note: run `una explain U1002` for an explanation
───╯

The diagnostic marks both lines: where the name was first defined, and where it was made again. Its scope is the stretch of code where a name can be used: here, the body of main. Some languages allow the second let, which shadows the first: the old value is still there, hidden behind the new one. Una does not, in a block or in a block nested in it, such as a loop's body. So a name means one thing from its line to the end of its block. To change a value, use let edit and an assignment; for a different value, choose a different name.

9.2.5.3 An editable name keeps its type

let edit items = 0 makes items an Int for good. Assign it a text:

src/till.unadiff
--- a/src/till.una
+++ b/src/till.una
@@ -10,3 +10,3 @@
   total = total + lamp
-  items = items + 1
+  items = "one"
   total = total + lamp
Diagnostic
[U2001] Error: expected `Int`, found `Text`

The checker expected an Int, the type of items, and found a Text. Every value an editable name takes must have the type it was declared with.

9.2.5.4 A name made in the body is new at each turn

A let inside a loop's body, such as let price in print_sale (section 9.1), is made afresh at each turn and is gone after it. It is a plain name: within its turn it does not change. To carry a value from one turn to the next, or out of the loop, declare it before the loop with let edit.

9.2.5.5 The loop variable is not editable

The loop variable is a plain name: each turn gives it the next value, and the body only reads it. Assign it, to skip a week:

src/counts.unadiff
--- a/src/counts.una
+++ b/src/counts.una
@@ -13,2 +13,3 @@
     total = total + per_week
+    week = week + 1
   total
Diagnostic
[U2019] Error: `week` is the variable of a `for` loop, which is read-only; bind a copy in the body with `let edit`, as `let edit next_week = week`

The message says why: the loop owns its variable, which is read-only, so it cannot be declared let edit. What it offers is a copy, let edit next_week = week, a new name in the body that starts at the loop variable's value and may change within the turn; it does not change the turns the loop takes. To skip turns, put the steps under an if; to walk every second week, compute it from the loop variable, such as let other = week * 2.

9.2.5.6 The range is fixed before the first turn

A loop computes its range once, before the first turn. A body that changes a name used in the range does not change how many turns the loop takes:

steps/14-accumulators/src/counts.unauna
--- How many turns a loop takes when its body moves the end of its own range: the range
--- was computed before the first turn, so the change does not add a turn.
pub turns_taken(last: Int) -> Int
=
  let edit end = last
  let edit turns = 0
  for aisle in 1..end
    end = end + 1
    turns = turns + 1
  turns
Output
turns of 1..3: 3

Each turn moves end one further, and the loop still takes the 3 turns of 1..3, the range it had when it started.

Note

let edit belongs to edition 0.2 and later. In a package of edition 0.1, edit is a reserved word, and every name is a plain let.

9.2.6 Choosing between let and let edit

Which to use:

You want to… Use
Name a value you compute once let
Keep a total, a count, a flag or a text that a loop builds let edit, declared before the loop
Name a value for one turn of a loop let, inside the body
Say what type a name holds let name: Type = …, with either form
A value that differs by case let with an if … then … else, not a let edit assigned in two places

Prefer let. A name that cannot change is one less thing a reader must track, and in most functions every name can be a plain let. Use let edit when a value really accumulates, as total does in a loop.

9.2.7 Check yourself: names

A shelf holds 10 units. Three are sold, then a delivery brings five:

src/restock.unauna
module restock

--- Prints the stock of a shelf after a sale and a delivery.
pub main() -> Unit
  uses @console: Console[print]
=
  let edit stock = 10
  stock = stock - 3
  let sold = 10 - stock
  stock = stock + 5
  @console.print("{stock} in stock, {sold} sold")

What does it print?

Show the answer
Output
12 in stock, 3 sold

stock goes 10, 7, 12. sold is computed once, when stock is 7, so it is 3, and it stays 3 when stock changes later: a plain let holds the value it was given, not a formula.

Next:9.3 What a loop keeps and what the verifier knows