---
title: "9.1 for over ranges and texts"
url: https://una-lang.org/en/learn/loops/for-over-ranges-and-texts/
release: v0.4.0
edition: "0.2"
---

# 9.1 for over ranges and texts

## 9.1.1 What a loop is

A **loop** runs the same steps several times, once for each value of a group. Think of a store clerk who counts stock aisle by aisle. The instruction is not "count aisle 1, then count aisle 2, then count aisle 3". It is "for each aisle from 1 to 3, count its shelves": one instruction, the same steps, and the aisle changes at each step. The instruction stays the same for a store of three aisles or of thirty.

A few words name the parts of a loop, and the rest of this chapter uses them:

- The **body** is the indented block of lines under the loop's first line: the steps to repeat.
- A **turn** is one run of the body, for one value. A loop over the aisles 1 to 3 takes three turns. (Other books call a turn an *iteration*.)
- The **loop variable** is the name the body uses for the value of the current turn. You choose it, and each turn gives it the next value.
- What the loop **walks** is the group it takes the values from: a **range** of whole numbers, such as 1 to 3, or the characters of a text.

## 9.1.2 Why programs repeat work

Here is a plan for four weeks, without a loop:

```una include="steps/01-no-loop/src/plan.una" title="src/plan.una" verified="check, run"
module plan

--- Prints a restock plan of four weeks, one line for each week, written out by hand.
pub main() -> Unit
  uses @console: Console[print]
=
  @console.print("week 1: count the lamp shelf")
  @console.print("week 2: count the lamp shelf")
  @console.print("week 3: count the lamp shelf")
  @console.print("week 4: count the lamp shelf")
```

Each example of this chapter is a package of its own, made as [chapter 2](https://una-lang.org/en/learn/numbers/values-types-and-names-let/#each-step-is-a-package) explains, and the chapter's download, `09-loops.tar.gz`, holds them all. This one works, and `una run .` prints:

```text include="steps/01-no-loop/expected/output.txt"
week 1: count the lamp shelf
week 2: count the lamp shelf
week 3: count the lamp shelf
week 4: count the lamp shelf
```

But the program is fragile in three ways:

1. **It fits one size.** It plans exactly four weeks. A plan of six weeks needs two more lines, and a plan whose length comes from a parameter cannot be written this way at all: the number of lines is fixed when you write the code, not when it runs.
2. **It repeats itself.** The text of the line is written four times. To change it, you change four places, and a missed one prints two different lines in one plan.
3. **It grows with the work.** A plan of a year would be fifty-two lines that differ in one number.

A function that calls itself, as [section 6.1](https://una-lang.org/en/learn/functions/calls-in-depth-labels-the-order-of-evaluation-method-calls-on-your-own-kinds/#s6-1) showed with `marked_down`, can repeat a step a number of times that comes from a parameter. A loop says the same thing more directly: do these steps for each week from 1 to `weeks`.

## 9.1.3 How to write a `for` loop

Here is the plan with a loop:

:::steps
```una include="steps/02-for/src/plan.una#print_weeks" title="src/plan.una"
--- Prints the line of each week of the plan, from week 1 to week `weeks`.
pub print_weeks(weeks: Int) -> Unit
  uses @console: Console[print]
=
  for week in 1..weeks
    @console.print("week {week}: count the lamp shelf")
```

1. **`for`.** The keyword that starts a loop.
2. **`week`.** The loop variable. You choose the name; a good name says what one value is.
3. **`in 1..weeks`.** What the loop walks: here the range of whole numbers from 1 to `weeks`, both included.
4. **`@console.print("week {week}: count the lamp shelf")`.** The body, indented two spaces under the `for` line. It runs once for each number of the range, with `week` holding that number.
:::

`main` calls `print_weeks(4)`, and `una run .` prints the same four lines as the plan written by hand:

```text include="steps/02-for/expected/output.txt"
week 1: count the lamp shelf
week 2: count the lamp shelf
week 3: count the lamp shelf
week 4: count the lamp shelf
```

Follow it turn by turn. The range `1..4` holds the numbers 1, 2, 3 and 4. The first turn gives `week` the value 1, and the body prints `week 1: …`. The second turn gives it 2, and so on. After the turn for 4 there is no number left, the loop ends, and so does `print_weeks`. The text of the line is written once, and `print_weeks(6)` plans six weeks with no change to the function.

## 9.1.4 What a loop can walk

What comes after `in` decides which values the loop visits. Each form below is a function of one package, `steps/03-range-forms`, whose `main` calls them with a few pairs of ends.

### 9.1.4.1 An inclusive range: `..`

`first..last` is the range from `first` to `last`, **both included**:

```una include="steps/03-range-forms/src/aisles.una#through" title="steps/03-range-forms/src/aisles.una"
--- Prints the aisles from `first` to `last`, `last` included: an inclusive range.
pub through(first: Int, last: Int) -> Unit
  uses @console: Console[print]
=
  @console.print("{first}..{last}:")
  for aisle in first..last
    @console.print("  aisle {aisle}")
```

`through(1, last: 3)` prints:

```text include="steps/03-range-forms/expected/output.txt#L1-L4"
1..3:
  aisle 1
  aisle 2
  aisle 3
```

### 9.1.4.2 An exclusive range: `..<`

`first..<last` is the range from `first` up to `last`, **with `last` left out**. Read `..<` as "up to, but less than":

```una include="steps/03-range-forms/src/aisles.una#before" title="steps/03-range-forms/src/aisles.una"
--- Prints the aisles from `first` up to `last`, `last` left out: an exclusive range.
pub before(first: Int, last: Int) -> Unit
  uses @console: Console[print]
=
  @console.print("{first}..<{last}:")
  for aisle in first..<last
    @console.print("  aisle {aisle}")
```

`before(1, last: 3)` prints:

```text include="steps/03-range-forms/expected/output.txt#L5-L7"
1..<3:
  aisle 1
  aisle 2
```

The exclusive form fits a count of things numbered from 0: `0..<count` takes exactly `count` turns, for the numbers 0 to `count - 1`.

### 9.1.4.3 Ends that are computed

The ends of a range may be any expressions that give whole numbers, such as a parameter plus 1. Both ends have one type, here `Int`:

```una include="steps/03-range-forms/src/aisles.una#next_two" title="steps/03-range-forms/src/aisles.una"
--- Prints the two aisles after `aisle`: the ends of a range may be computed.
pub next_two(aisle: Int) -> Unit
  uses @console: Console[print]
=
  @console.print("after aisle {aisle}:")
  for next in aisle + 1..aisle + 2
    @console.print("  aisle {next}")
```

`next_two(4)` prints:

```text include="steps/03-range-forms/expected/output.txt#L16-L18"
after aisle 4:
  aisle 5
  aisle 6
```

A range may also start below zero: `through(-1, last: 1)` visits -1, 0 and 1.

### 9.1.4.4 A range of a fixed-width type

The ends may be of a fixed-width type, such as `U8` ([section 2.3](https://una-lang.org/en/learn/numbers/fixed-width-integers/#s2-3)). A literal end then takes the type of the other end, so in `first..255` the `255` is a `U8` too:

```una include="steps/03-range-forms/src/aisles.una#last_codes" title="steps/03-range-forms/src/aisles.una"
--- Prints the last two label codes of a roll, which fit in one byte: a range of `U8`.
pub last_codes() -> Unit
  uses @console: Console[print]
=
  let first: U8 = 254
  @console.print("codes from {first}:")
  for code in first..255
    @console.print("  code {code}")
```

```text include="steps/03-range-forms/expected/output.txt#L19-L21"
codes from 254:
  code 254
  code 255
```

An inclusive range stops at its end without computing the number after it, so a range up to 255, the largest `U8`, does not overflow.

### 9.1.4.5 The characters of a text: `chars`

`sku.chars()` gives the characters of a text, in order, each one a text of one character. A loop walks them one by one:

```una include="steps/04-texts/src/skus.una#print_characters" title="steps/04-texts/src/skus.una"
--- Prints each character of a SKU, between brackets.
pub print_characters(sku: Text) -> Unit
  uses @console: Console[print]
=
  for character in sku.chars()
    @console.print("[{character}]")
```

`print_characters("Café-2")` prints:

```text include="steps/04-texts/expected/output.txt#L1-L6"
[C]
[a]
[f]
[é]
[-]
[2]
```

`é` is one character, as `.len` counts it ([section 3.1](https://una-lang.org/en/learn/text-and-conditions/text/#s3-1)), and so is the dash. What `chars` gives back is a **list** of texts, a sequence of values; lists are the subject of [chapter 10](https://una-lang.org/en/learn/collections/lists/#s10-1), which also shows a loop over any list. Here you need only what the loop does with it: one turn per character.

### 9.1.4.6 The parts of a text: `split`

`sku.split(on: "-")` cuts a text at each dash and gives the parts between them, also as a list of texts ([section 3.2](https://una-lang.org/en/learn/text-and-conditions/working-with-text-the-preludes-functions-and-method-calls/#s3-2) lists it):

```una include="steps/04-texts/src/skus.una#print_parts" title="steps/04-texts/src/skus.una"
--- Prints each part of a SKU, the texts between its dashes.
pub print_parts(sku: Text) -> Unit
  uses @console: Console[print]
=
  for part in sku.split(on: "-")
    @console.print("part: {part}")
```

`print_parts("LAMP-01-BR")` prints:

```text include="steps/04-texts/expected/output.txt#L7-L9"
part: LAMP
part: 01
part: BR
```

### 9.1.4.7 The positions of a text

A text's characters sit at positions numbered from 0, so `0..<sku.len` walks the positions of a text, from the first to the last:

```una include="steps/04-texts/src/skus.una#print_positions" title="steps/04-texts/src/skus.una"
--- Prints each position of a SKU, from 0 up to its length.
pub print_positions(sku: Text) -> Unit
  uses @console: Console[print]
=
  for position in 0..<sku.len
    @console.print("position {position} of {sku.len}")
```

`print_positions("RUG")` prints:

```text include="steps/04-texts/expected/output.txt#L10-L12"
position 0 of 3
position 1 of 3
position 2 of 3
```

A text of 3 characters has the positions 0, 1 and 2. With `..` in place of `..<`, the loop would also visit 3, a position past the end. [What the body knows](https://una-lang.org/en/learn/loops/what-a-loop-keeps-and-what-the-verifier-knows/#what-the-body-knows) shows how the verifier catches that when the body cuts the text at the position.

## 9.1.5 What a loop body can hold

The body of a loop is a block like the body of a function: it may hold a `let`, an `if`, a `when`, and another loop. The step for this part plans a store's week:

```una include="steps/05-bodies/src/week.una#Day..day_kind" title="steps/05-bodies/src/week.una" caption="the days"
--- The kind of a day of the week, for the store's hours.
kind Day = Weekday | Saturday | Sunday

--- The kind of day `day` is, counting Monday as day 1.
pub day_kind(day: Int) -> Day = if day == 6 then Saturday else if day == 7 then Sunday else Weekday
```

### 9.1.5.1 A `when` in the body

A `when` inside the body chooses, at each turn, by the variant of a sum kind ([section 4.3](https://una-lang.org/en/learn/kinds/taking-a-sum-apart-when/#s4-3)):

```una include="steps/05-bodies/src/week.una#print_hours" title="steps/05-bodies/src/week.una"
--- Prints the hours of each day: a `when` inside a loop.
pub print_hours() -> Unit
  uses @console: Console[print]
=
  for day in 1..7
    when day_kind(day)
      is Weekday -> @console.print("day {day}: 9:00 to 18:00")
      is Saturday -> @console.print("day {day}: 10:00 to 16:00")
      is Sunday -> @console.print("day {day}: closed")
```

```text include="steps/05-bodies/expected/output.txt#L1-L7"
day 1: 9:00 to 18:00
day 2: 9:00 to 18:00
day 3: 9:00 to 18:00
day 4: 9:00 to 18:00
day 5: 9:00 to 18:00
day 6: 10:00 to 16:00
day 7: closed
```

### 9.1.5.2 An `if` in the body

An `if` without `else` inside the body runs its own lines only on the turns where its condition holds ([section 8.1](https://una-lang.org/en/learn/choices/every-form-of-if/#s8-1)):

```una include="steps/05-bodies/src/week.una#print_deliveries" title="steps/05-bodies/src/week.una"
--- Prints the days a delivery comes, Tuesday and Thursday: an `if` inside a loop.
pub print_deliveries() -> Unit
  uses @console: Console[print]
=
  for day in 1..7
    if day == 2 or day == 4
      @console.print("day {day}: delivery")
```

```text include="steps/05-bodies/expected/output.txt#L8-L9"
day 2: delivery
day 4: delivery
```

Seven turns run, and two of them print. This is how a loop skips a value: the steps that should not run for it go under an `if`.

### 9.1.5.3 A `let` in the body

A `let` inside the body names a value for one turn. Each turn computes it afresh, from that turn's `week`:

```una include="steps/05-bodies/src/week.una#print_sale" title="steps/05-bodies/src/week.una"
--- Prints the price of a lamp in each of three weeks of a sale: a `let` inside a loop.
pub print_sale(cents: Int) -> Unit
  uses @console: Console[print]
=
  for week in 1..3
    let off = week * 10
    let price = cents - cents * off / 100
    @console.print("week {week}: {off}% off, {price} cents")
```

`print_sale(2_000)` prints:

```text include="steps/05-bodies/expected/output.txt#L10-L12"
week 1: 10% off, 1800 cents
week 2: 20% off, 1600 cents
week 3: 30% off, 1400 cents
```

### 9.1.5.4 A loop inside a loop

A body may hold another loop. The inner loop runs all its turns during each turn of the outer one, so 2 aisles of 3 shelves give 6 turns of the inner body:

```una include="steps/05-bodies/src/week.una#print_shelf_codes" title="steps/05-bodies/src/week.una"
--- Prints the code of every shelf of the first aisles: a loop inside a loop.
pub print_shelf_codes(aisles: Int, shelves: Int) -> Unit
  uses @console: Console[print]
=
  for aisle in 1..aisles
    for shelf in 1..shelves
      @console.print("A{aisle}-S{shelf}")
```

`print_shelf_codes(2, shelves: 3)` prints:

```text include="steps/05-bodies/expected/output.txt#L13-L18"
A1-S1
A1-S2
A1-S3
A2-S1
A2-S2
A2-S3
```

All the shelves of aisle 1 come first, then all the shelves of aisle 2: the outer loop moves on only when the inner one has finished.

## 9.1.6 How a loop behaves

### 9.1.6.1 Order, and how many turns

- A loop over a range visits its numbers in increasing order, each one once.
- A loop over the characters or the parts of a text visits them in the text's order.
- The range, or the list, is computed once, before the first turn. So the number of turns is fixed when the loop starts. [Section 9.2](https://una-lang.org/en/learn/loops/names-that-change-let-edit/#s9-2) shows that changing a name inside the body does not change it.

### 9.1.6.2 An empty range runs no turn

A range from a number to itself visits that number once with `..`, and nothing with `..<`. A range whose start is above its end visits nothing: Una never counts down. The calls `through(2, last: 2)`, `before(2, last: 2)` and `through(3, last: 1)` each print their heading, and only the first prints an aisle under it:

```text include="steps/03-range-forms/expected/output.txt#L8-L11"
2..2:
  aisle 2
2..<2:
3..1:
```

The same holds for a text: the empty text, `""`, has no characters, and a loop over `"".chars()` runs its body zero times.

### 9.1.6.3 A text is walked through `chars`, not by itself

A loop walks a range or a list, and a text is neither. Write `for character in sku` in `print_characters`, and `una check .` reports:

```text include="steps/06-text-itself/expected/rendered.txt"
[U2001] Error: expected `List[_]`, found `Text`
   ╭─[ src/skus.una:7:20 ]
   │
 7 │   for character in sku
   │                    ─┬─
   │                     ╰─── expected `List[_]`, found `Text`
   │
   │ Note: run `una explain U2001` for an explanation
───╯
```

The checker expected a list, `List[_]`, after `in`, and found a `Text`. Write `sku.chars()`, which gives the list of its characters.

### 9.1.6.4 A body has at least one line

The body is the indented block under the `for` line, and it cannot be empty. Leave the line of `print_weeks` unindented, and the loop has no body:

```text include="steps/07-empty-body/expected/rendered.txt#L1"
[U0101] Error: unexpected `@console`, expected an indented block
```

The line after `for` must be indented two spaces deeper than the `for` line.

### 9.1.6.5 Every turn runs

Una has no `break`, which other languages use to leave a loop early, and no `continue`, which skips the rest of a turn. Every turn of the range runs its body. To skip a value, put the steps under an `if`, as `print_deliveries` does.

### 9.1.6.6 A loop is a step, not a value

A `for` loop gives no value of its own: it is a **statement**, a step of a block that does something instead of giving a value. What a loop computes either goes out through its steps, as the printing loops of this section do, or stays in names that its body changes, which [section 9.2](https://una-lang.org/en/learn/loops/names-that-change-let-edit/#s9-2) introduces. A function whose result is `Unit` may end with a loop, as `print_weeks` does.

A loop's turns are not calls of a function, so a long loop does not count toward the limit on how many calls may wait at once, which [section 16.4](https://una-lang.org/en/learn/memory/limits-call-depth-and-memory/#s16-4) explains.

## 9.1.7 Una has no `while`

Many languages have a second kind of loop, `while`, which repeats its body for as long as a condition holds. Its end depends on the body changing something that the condition reads. When the body forgets to, the loop never ends, and the program hangs.

Una has no `while`. Write one anyway, in a `main` that counts how long the stock lasts:

```diff include="steps/08-weeks-of-stock..steps/09-while:src/stock.una" context="1" title="src/stock.una"
--- a/src/stock.una
+++ b/src/stock.una
@@ -13,3 +13,4 @@
 =
-  @console.print("10 units at 3 a week last {weeks_of_stock(10, per_week: 3)} weeks")
-  @console.print("2 units at 3 a week last {weeks_of_stock(2, per_week: 3)} weeks")
+  let stock = 10
+  while stock >= 3
+    @console.print("one more week")
```

`una check .` reports:

```text include="steps/09-while/expected/rendered.txt"
[U0103] Error: `while` is not a keyword in Una; use `for` or recursion
    ╭─[ src/stock.una:15:3 ]
    │
 15 │   while stock >= 3
    │   ──┬──
    │     ╰──── `while` is not a keyword in Una; use `for` or recursion
    │
    │ Note: run `una explain U0103` for an explanation
────╯
```

The message names the two ways Una repeats work: `for`, and **recursion**, a function that calls itself ([section 6.1](https://una-lang.org/en/learn/functions/calls-in-depth-labels-the-order-of-evaluation-method-calls-on-your-own-kinds/#s6-1)). This `while` is the bug of the first paragraph, too: its body never lowers `stock`, so the condition never turns false. How many weeks the stock lasts is not known before the loop starts, so a range does not fit, and recursion does:

```una include="steps/08-weeks-of-stock/src/stock.una#weeks_of_stock" title="steps/08-weeks-of-stock/src/stock.una"
--- How many whole weeks `stock` units last when `per_week` units sell each week: a
--- function that calls itself, with less stock each time.
pub weeks_of_stock(stock: Int, per_week: Int) -> Int
  requires per_week >= 1
=
  if stock < per_week then 0 else 1 + weeks_of_stock(stock - per_week, per_week: per_week)
```

```text include="steps/08-weeks-of-stock/expected/output.txt"
10 units at 3 a week last 3 weeks
2 units at 3 a week last 0 weeks
```

With 10 units and 3 sold a week, the function answers 1 + the weeks of 7 units, which is 1 + the weeks of 4 units, which is 1 + the weeks of 1 unit, which is 0: 3 weeks. Each call has less stock, so the calls end, and `requires per_week >= 1` keeps a caller from passing 0, which would never lower the stock ([section 5.1](https://una-lang.org/en/learn/contracts/preconditions-requires/#s5-1)). When you know an upper limit, such as "at most 52 weeks", a range up to that limit with an `if` in the body is the other choice.

Edition `0.2` has no loop that ends on a condition, rather than after a number of turns fixed before it starts. Edition `0.4`, a preview, adds `stop when` and `for ever`.

## 9.1.8 Choosing a range, the characters or recursion

:::decide
**Which to use:**

| You want to… | Use |
| --- | --- |
| Repeat steps a number of times, counting from 1 | `for n in 1..count` |
| Visit the positions of something numbered from 0 | `for position in 0..<count` |
| Visit each character of a text | `for character in text.chars()` |
| Visit the parts of a text between separators | `for part in text.split(on: separator)` |
| Run some steps only for some turns | an `if` without `else` in the body |
| Repeat until something happens, with no limit known in advance | recursion, with a case that stops it |
| Visit each element of a list | `for` over the list ([section 10.1](https://una-lang.org/en/learn/collections/lists/#s10-1)) |
:::

## 9.1.9 Check yourself: loops

This program prints the shelves to count this morning:

```una include="steps/10-check-ranges/src/shelves.una" title="src/shelves.una"
module shelves

--- Prints the shelves to count this morning.
pub main() -> Unit
  uses @console: Console[print]
=
  for aisle in 1..2
    for shelf in 2..<4
      @console.print("{aisle}-{shelf}")
  for aisle in 5..4
    @console.print("aisle {aisle}")
  @console.print("done")
```

What does `una run .` print?

:::answer Show the answer
```text include="steps/10-check-ranges/expected/output.txt"
1-2
1-3
2-2
2-3
done
```

The outer loop takes two turns, for aisles 1 and 2. In each, the inner range `2..<4` gives the shelves 2 and 3, since `..<` leaves 4 out. The second loop's range, `5..4`, starts above its end, so it runs no turn, and the program goes on to `done`.
:::
