---
title: "Expressions and control flow"
url: https://una-lang.org/en/docs/language/control-flow/
release: v0.4.0
source: https://github.com/una-lang/una/blob/v0.4.0/docs/guide/syntax-reference.md
---

# Expressions and control flow

## 5.1 Blocks, `let` and statements

A block is a sequence of statements followed by a final expression, which is the block's value.

```una
module demo

pub kind Seats = Int in 0..5000

pub kind Availability = SoldOut | Few | Open

pub kind Event
  name: Text
  remaining: Seats

clamp_seats(raw: Int) -> Seats = if raw < 0 then 0 else if raw > 5000 then 5000 else raw

availability(e: Event) -> Availability = if e.remaining == 0 then SoldOut else if e.remaining < 20 then Few else Open

pub status(n: Text, raw: Int) -> Availability
=
  let seats = clamp_seats(raw)
  let event: Event = Event(name: n, remaining: seats)
  availability(event)
```

- A plain `let` is immutable. An editable binding is declared `let edit` (§5.6).
- A statement that is not a `let`, an assignment, a `for` loop, a `together` block or an `if` without `else` must have type `Unit` (U2011). To ignore a value, bind it.
- A `let` whose right-hand side is in RL keeps an exact fact that later proofs can use: after `let half = total / 2`, the verifier knows `half == total / 2`. A `let` bound to a function call keeps only what that function's `ensures` promises.

## 5.2 `if`

```una
module demo

pub size(n: Int) -> Text = if n > 100 then "large" else "small"

pub band(n: Int) -> Text
=
  if n > 100
    "large"
  else if n > 10
    "medium"
  else
    "small"
```

- `if` used as an expression always has an `else`.
- In edition `0.2`, a block-form `if` without `else` is a statement of type `Unit`, used to update editable bindings (§5.5).

## 5.3 `when`

```una
module demo

pub kind Seats = Int in 0..5000

pub kind Availability = SoldOut | Few | Open

pub kind Registration
  name: Text

pub kind Lookup = Found(registration: Registration) | Missing

--- Variants.
pub label(status: Availability) -> Text
=
  when status
    is SoldOut -> "sold out"
    is Few -> "few seats left"
    is Open -> "open"

--- A payload bound by its field name, or under another name.
pub name_of(lookup: Lookup) -> Text
=
  when lookup
    is Found(registration) -> registration.name
    is Missing -> "unknown"

pub name_again(lookup: Lookup) -> Text
=
  when lookup
    is Found(registration: r) -> r.name
    is Missing -> "unknown"

--- Ranges, proven to cover every `Seats` value.
pub band(remaining: Seats) -> Availability
=
  when remaining
    in 0..0 -> SoldOut
    in 1..<20 -> Few
    in 20..5000 -> Open

--- Literals, with `else`.
pub reason(code: Int) -> Text
=
  when code
    is 200 -> "ok"
    is 404 -> "not found"
    else -> "other"

--- A block arm.
pub greeting(status: Availability) -> Text
=
  when status
    is SoldOut ->
      let note = "try another date"
      note
    else -> "welcome"
```

Rules:

- **Variant arms** must be exhaustive, or end with `else` (U2007).
- **Range and literal arms** without `else` create an obligation: the compiler must prove the arms cover every value the subject can take. With `Seats = Int in 0..5000`, the three ranges above are proven exhaustive. Arms over a fixed-width value take its type, and a bound that does not fit is U2022.
- **`else` must be the last arm,** and unreachable arms are rejected (U2008).
- **Single-field variants** bind their field under any name: `is Some(r)`.
- **Results of `attempt`** are matched with `is Ok(value)` and `is Err(failure)` (§6.4).

## 5.4 One effect per line

A capability operation, a call to a function that uses capabilities or can fail, or a call with an `edit` or `take` argument, must be the **whole expression** of a statement, a `let` or a final expression, optionally wrapped in `attempt` (U3013). It cannot be nested inside another expression.

```una
module demo

pub kind Availability = SoldOut | Few | Open

pub kind Registration
  name: Text
  status: Availability

pub kind StoreError = | Timeout

pub kind CheckInError = NotRegistered | Unavailable

pub capability Registrations
  op find(key: Text) -> Option[Registration]
    fails StoreError

pub status_of(key: Text) -> Availability
  uses @registrations: Registrations[find]
  fails CheckInError
=
  let registration = @registrations.find(key)
    if error fail Unavailable
    if none fail NotRegistered
  registration.status
```

```una
-- fails with U3013
module demo

pub capability Store
  op get(key: Text) -> Int

double(x: Int) -> Int = x * 2

pub doubled(key: Text) -> Int
  uses @store: Store[get]
=
  double(@store.get(key))
```

This fixes evaluation order, gives every failure a handling site and makes every effect visible on its own line. Pure calls nest freely. Example `do` lines are exempt (§10).

## 5.5 `for` loops (edition `0.2`)

`for x in xs` visits the elements of a list in order, and `for i in a..<b` or `for i in a..b` the integers of a range in increasing order (`spec/17 §1`, `§4`).

```una
module demo

--- A `for` loop over a list, updating a `let edit` binding.
pub total(xs: List[Int]) -> Int
=
  let edit sum = 0
  for x in xs
    sum = sum + x
  sum

--- Over a range: `a..<b` excludes `b`, `a..b` includes it. The bounds are evaluated once.
pub squares(n: Int) -> List[Int]
=
  let edit out: List[Int] = []
  for i in 0..<n
    out = out.append(item: i * i)
  out

--- The loop variable takes the integer type of the bounds: here `U8`.
pub bytes(low: U8, high: U8) -> List[U8]
=
  let edit out: List[U8] = []
  for b in low..high
    out = out.append(item: b)
  out

--- An `if` without `else` is a statement.
pub count_large(xs: List[Int], limit: Int) -> Int
=
  let edit count = 0
  for x in xs
    if x > limit
      count = count + 1
  count
```

- **The bounds,** and the list, are evaluated once, before the first iteration. There is no `break` and no `continue`.
- **The loop variable** is a plain binding (U2019 on assignment). A range's bounds are integers of one type, `Int` or a fixed-width type, and a literal bound takes the type of the other, so `for b in low..high` over `U8` bounds gives `b: U8`. An inclusive range ends at its upper bound without computing its successor, so `0..255` over `U8` does not overflow.
- **As a statement,** a loop has the value `unit`. It updates `let edit` bindings declared before it.
- **Verification.** The refinements of the bindings the loop updates are its invariant: the body is checked once, for any iteration, with those bindings fresh at their declared types, and no fact about their values survives the loop. Inside a range loop, `a <= i < b` (or `<= b`) holds. There is no `invariant` clause.
- **Failures** inside the body end the loop and the function; the bindings it updated keep their values from before the loop (§5.6).
- **Labels.** A loop over a list runs under the top label of the list, and a range loop under the labels of its bounds. In such a body, `fail` and calls that can fail are U4002 when that label is not `public`.
- **Edition `0.4`** adds `stop` and `skip`, which end a loop or an iteration early, `for until c decreases m`, which runs until `c` holds, and `for ever` with `on stop` in a function that says `diverges`, which runs until it is stopped (`spec/26 §3` to `§6`). See [Loops that run until stopped](https://una-lang.org/en/docs/language/control-flow/for-ever/).

## 5.6 Mutable value semantics (edition `0.2`)

Una has no references and no lifetimes: values stay values, and a binding declared editable can be rebound (ADR 0056, `spec/17`).

- **`let edit x = e`** declares an editable binding, and `x = e` rebinds it. A **place** is an editable binding or a field path of one: `t.last = value` rebuilds `t` with that field changed. Assigning anything else is U2019.
- **Fixed type.** An editable binding keeps its declared type, refinement and label at every rebind; each rebind carries the refinement obligation of an annotated `let`. Without an annotation, its type is that of its initial value without its refinement.
- **`edit` parameters** are passed in and out: `record(edit t: Tally, ...)` receives the caller's value and returns its final value. The caller writes `edit t` at the argument (U2020 for a missing or extra marker), and the argument is a place. In `ensures`, `t` is the final value and `old(t)` the value on entry.
- **`take` parameters** consume their argument: after `f(take a)`, using `a` is U2017 until an assignment gives it a new value.
- **Exclusivity.** An `edit p` argument together with any other use of the root binding of `p` in the same call is U2018.
- **Lists** change through `set` and `append`: `edit ys.set(index: i, item: v)`, with `requires 0 <= index and index < xs.len`.
- **Transactional values.** A call that fails leaves its `edit` arguments unchanged for the caller. Effects already performed stay performed.
- **Operations and handlers** cannot declare `edit` or `take` parameters (U2020).

```una
module demo

pub kind Tally
  seen: Int
  last: Int

--- An `edit` parameter is passed in and out; `old(t)` is its value on entry.
pub record(edit t: Tally, value: Int) -> Unit
  ensures t.seen == old(t).seen + 1
=
  t.seen = t.seen + 1
  t.last = value

pub tally(xs: List[Int]) -> Tally
=
  let edit t = Tally(seen: 0, last: 0)
  for x in xs
    edit t.record(value: x)
  t

--- `take` consumes its argument: the caller cannot use it afterwards.
pub finish(take t: Tally) -> Int = t.seen

pub summary(xs: List[Int]) -> Int
=
  let t = tally(xs)
  let n = finish(take t)
  n

--- List elements change through `set`.
pub reset_first(xs: List[Int]) -> List[Int]
=
  let edit ys = xs
  if ys.len > 0
    edit ys.set(index: 0, item: 0)
  ys
```

```una
-- fails with U2017
module demo

pub finish(take xs: List[Int]) -> Int = xs.len

pub twice(xs: List[Int]) -> Int
=
  let n = finish(take xs)
  xs.len + n
```

```una
-- fails with U2019
module demo

pub bump(x: Int) -> Int
=
  let n = x
  n = n + 1
  n
```

A backend may update a uniquely held value in place, and reuse the memory of a value passed by `take`. None of this is observable.

## 5.7 Concurrent tasks with `together` (edition `0.2`)

`together` runs independent work as concurrent tasks, and every task ends before its block does (ADR 0065, `spec/19`). A program's result and its trace are those of running the tasks one after another, in order.

```una
module demo

pub capability Sensor
  op reading() -> Int

pub kind FetchError = Missing | Gone

handler fixed(value: Int) for Sensor
  op reading() = value

pub warmest() -> Int
  uses @north: Sensor[reading]
  uses @south: Sensor[reading]
=
  together
    let north = reading() with @sensor = @north
    let south = reading() with @sensor = @south
  max(north, b: south)

reading() -> Int
  uses @sensor: Sensor[reading]
=
  @sensor.reading()

fetch(id: Int) -> Int
  fails FetchError
=
  if id < 0
    fail Missing
  else
    id * 10

--- One task per element; the results come back in list order.
pub pages(ids: List[Int]) -> List[Int]
  fails FetchError
=
  let pages = together for id in ids
    fetch(id)
      if error pass
  pages

--- Over a range, the variable takes the integer type of the bounds.
pub doubled(n: U8) -> List[Int]
=
  let out = together for i in 0..<n
    i.to_int() * 2
  out
```

- **`together`** is a statement whose indented body holds two or more `let` statements, its **branches** (U2024 otherwise). Each branch's expression, with its `with` bindings and its handling clauses, runs as a task. The branches' bindings are in scope after the block.
- **`together for x in xs`** stands where a `let` value can, and runs one task per element of a list or of a range. Its body is a block, and the result is the list of the body's values, in element order. Over a range, `x` takes the integer type of the bounds, as in a `for` loop.
- **Handling clauses** go on their own indented lines below the call, as everywhere (§6.3).
- **Captures.** A task sees the bindings before the block, never its siblings', and captures their values. Assigning a binding declared outside the task, or passing it as `edit` or `take`, is U2023: return new values from the task instead.
- **Capabilities** in scope can be used by every task, and so can `uses of` parameters.
- **Failures.** When a task fails, the tasks after it are canceled, and the block fails with the failure of the lowest-indexed failing task, as running the tasks one after another would. A canceled task stops at its next call, operation or loop iteration; an operation in progress completes.
- **Labels.** `together for` runs its tasks under the top label of its list, or the labels of its range bounds, as a `for` loop does, and its result carries that label.
- **Traces** list the events of the tasks in task order, each with its task's path, as `"task": "2.1"`. A canceled task that had started ends with a `cancelled` event.
- **Runtimes.** The interpreter runs the tasks one after another. A native executable runs the tasks on `--workers` threads, one per core by default, so the lines that tasks print may interleave.

```una
-- fails with U2023
module demo

bump(edit n: Int) -> Int
=
  n = n + 1
  n

pub count(xs: List[Int]) -> Int
=
  let edit seen = 0
  together
    let a = xs.len
    let b = bump(edit seen)
  seen + a + b
```

```una
-- fails with U2024
module demo

pub one() -> Int
=
  together
    let a = 1
  a
```

---


## Constructs

- [when](https://una-lang.org/en/docs/language/control-flow/when.md)
- [for](https://una-lang.org/en/docs/language/control-flow/for.md)
- [let edit and edit parameters](https://una-lang.org/en/docs/language/control-flow/let-edit.md)
- [take](https://una-lang.org/en/docs/language/control-flow/take.md)
- [together](https://una-lang.org/en/docs/language/control-flow/together.md)
- [Loops that run until stopped: for ever, for until, stop and skip](https://una-lang.org/en/docs/language/control-flow/for-ever.md)
