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

# Functions and contracts

## 4.1 Two forms

```una
module demo

requirement EVENTS_3
  text "An event with no remaining seats is always shown as sold out"
  source policy "Box Office Handbook 2.1"
  owner box_office
  status active

pub kind Seats = Int in 0..5000

pub kind Availability = SoldOut | Few | Open

pub kind Event
  name: Text
  remaining: Seats

--- Short form.
double(x: Int) -> Int = x * 2

--- Long form.
pub availability(e: Event) -> Availability
  ensures e.remaining < 1 implies result is SoldOut
  derived from EVENTS_3
=
  when e.remaining
    in 0..0 -> SoldOut
    in 1..<20 -> Few
    in 20..5000 -> Open
```

- **Short form:** no clauses, and a body that is a single-line expression. A `with` clause belongs to a statement, not an expression, so a body with `with` needs the long form (U0101 otherwise, §7.4).
- **Long form:** the signature, then the indented clauses, then `=` alone on a line, then the indented body.

`una fmt` converts between them: a long form with no clauses and a one-line body becomes the short form.

## 4.2 Clauses

| Clause | Meaning | Checked how |
| --- | --- | --- |
| `requires p` | precondition over parameters | proven at every call site; assumed inside the body |
| `ensures q` | postcondition over parameters, `result` and `old(x)` | proven on every normal return path; assumed by callers |
| `uses @c: C[ops]` | may perform `ops` through capability `@c` | effects of the body must fit (U3003) |
| `uses of p` | may perform the effects of the function argument `p` (edition `0.2`) | U3017 to U3019 for a malformed clause |
| `fails E` | may fail with variants of sum kind `E` | failures of the body must be variants of `E` (U3009) |
| `fails of p` | may fail as the function argument `p` does (edition `0.2`) | as `uses of p` |
| `derived from R1, R2` | traceability to requirements | each requirement must exist (U1006) |

Rules:

- **Canonical order:** every `requires`, then every `ensures`, then every `uses` and `uses of` (one capability or parameter per clause), then at most one `fails` and one `fails of`, then at most one `derived from`. Anything else is U0102.
- **`requires` and `ensures`** must be in RL (U2014).
- **`result`** exists only in `ensures` clauses and example `expect` lines (U2012). **`old(x)`** exists only in `ensures`, on an `edit` parameter (§5.6).
- **`ensures` covers normal returns only;** failures carry no postcondition.
- **Partial correctness:** `ensures` holds if the function returns. Termination is not checked.
- **Pure means no `uses`.** A function without `uses` cannot contain any `@` (U3004).
- **No `fails` means it cannot fail.**

```una
module demo

pub kind Seats = Int in 0..5000

pub kind Event
  name: Text
  remaining: Seats

pub seats_after(e: Event, count: Int) -> Seats
  requires count >= 1
  requires count <= e.remaining
  ensures result == e.remaining - count
=
  e.remaining - count
```

The compiler proves that `e.remaining - count` fits `Seats` (between 0 and 5000) using both `requires` clauses, and proves the `ensures` clause. Every caller must prove both `requires` clauses at the call site.

**Effect polymorphism** (edition `0.2`, ADR 0062). `uses of p` and `fails of p` name a parameter `p` of function type, written without its own `uses` or `fails`. At each call, the callee's effects and failures are its own plus those of the argument passed for `p`. Inside the body, `p` is only called, or passed on to a parameter that the callee's `of` clause names. A callee with its own `fails E` accepts for `p` only an argument that fails with `E`, so each function keeps one error kind.

```una
module demo

pub kind ParseError = | NotANumber

--- `each` may have effects and may fail; `apply_all` has them too, at each call.
pub apply_all(xs: List[Text], each: fn(Text) -> Int) -> List[Int]
  uses of each
  fails of each
=
  xs.map(each: each)
    if error pass

pub parse(t: Text) -> Int
  fails ParseError
=
  t.to_int()
    if none fail NotANumber

pub parse_all(xs: List[Text]) -> List[Int]
  fails ParseError
=
  apply_all(xs, each: parse)
    if error pass

pub shout(names: List[Text]) -> Unit
  uses @console: Console[print]
=
  let printed = names.map(each: fn(n) -> @console.print(n))
  unit
```

## 4.3 Visibility and inference

- `pub` functions must declare every `uses`, their `fails` and the constraints of their type parameters explicitly. They are the reviewed boundary.
- Private functions may omit `uses`, `fails`, `uses of`, `fails of` and constraints; the compiler infers them. `una contract <name>` shows the inferred header.
- Parameter and result types are never inferred.

## 4.4 Calls and labeled arguments

| Rule | Example |
| --- | --- |
| One argument: the label is optional | `double(4)` |
| Two or more: the first may be unlabeled, the rest must be labeled (U2004) | `seats_after(event, count: 2)` |
| Punning: from the second argument on, a bare identifier equal to the parameter name counts as labeled; the first argument always binds the first parameter (ADR 0049) | `record(key, status)` |
| Argument count: too many arguments, or a parameter that receives none, is U2001. The count is checked before the labels. | `f(1, b: 2, b: 3)` for a two-parameter `f`: U2001 "`f` takes 2 arguments, but 3 are given", and no U2006 |
| Unknown label: U2005 | `f(1, c: 2)` |
| Duplicate argument, with the right count: U2006 | `f(a: 1, a: 2)` |
| Arguments are evaluated left to right | |

Constructors follow related rules:

- Records and variants with two or more fields need every field labeled (punning allowed). An unlabeled field is U2004 ("`P` has 2 fields, so every argument needs its field's label"); missing or unknown fields are U2009.
- Any order of labeled fields type-checks, but the canonical form is declaration order (§13): `una check` reports another order as U7001, and `una fmt` rewrites it.
- A single-field constructor may omit the label: `Some(r)`, `Ok(v)`. Extra arguments to a single-field constructor, and parentheses after a variant without fields, are U2009.
- A variant with fields is not a value on its own: `e == Found` is U2009, with the repair `e is Found`.

```una
module demo

pub kind Registration
  name: Text
  seat: Int

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

pub kind Event
  name: Text
  remaining: Int

pub sample(r: Registration) -> Lookup
=
  let e = Event(name: "Meetup", remaining: 120)
  let found = Found(registration: r)
  let maybe = Some(r)
  found
```

## 4.5 Method-call syntax

- `e.f(args)` calls `f(e, args)`. The receiver becomes the first, unlabeled argument.
- If `e` has a field `f` of function type, `e.f(args)` calls that field instead.
- `e.f` without arguments is field access, or `f(e)` when `e` has no field `f` and `f` is a function with one parameter.
- `.len` is built in for `Text` and `List`, and the conversions and arithmetic methods of §3.1 for integers.
- `edit xs.set(index: 0, item: v)` passes the receiver as an `edit` argument (§5.6).

```una
module demo

pub kind Event
  name: Text
  remaining: Int

pub open_names(schedule: List[Event]) -> Int
=
  let open_events = schedule.filter(keep: fn(e) -> e.remaining > 0)
  let names = open_events.map(each: fn(e) -> e.name)
  names.len
```

## 4.6 Lambdas and function types

```una
module demo

pub increments(xs: List[Int]) -> List[Int] = xs.map(each: fn(x) -> x + 1)

pub next() -> fn(Int) -> Int = fn(x: Int) -> x + 1
```

- A lambda's parameter types come from the expected type, as in `map`'s `each`; without one, annotate them (`fn(x: Int) -> x + 1`), or it is U2010.
- Function types are written `fn(A, B) -> C`, optionally with `uses` and `fails`: `fn(Text) -> Unit uses @log: Log[write]`.
- A lambda is **pure** unless its expected type declares `uses` or `fails`, or is a parameter named by a `uses of` or `fails of` clause.
- An effectful or fallible lambda is **second-class**: it may be passed as an argument, but not returned, stored or bound with `let` (U3006).
- **A lambda body is one expression, with no room for a handling clause.** So a lambda cannot call an operation or a function that can fail: `fn(k) -> @audit.record(k)`, where `record` declares `fails`, is U3007. A lambda may still fail directly, as in `fn(k) -> if k > 0 then k else fail Bad`, when its expected type declares `fails`. Put fallible work in a named function with handling clauses, and pass the function by name, as `apply_all(xs, each: parse)` in §4.2.
- Lambdas capture variables by value. A lambda captures the value an editable binding has when the lambda is created, and cannot assign it (U2019).
- **The prelude's higher-order functions** (`map`, `filter`, `fold`, `first_where`) declare `uses of` and `fails of` their function parameter in edition `0.2`, so `names.map(each: fn(n) -> @console.print(n))` works (§4.2). In edition `0.1` they accept only pure, non-failing lambdas (U3004 otherwise). Prefer a `for` loop for anything that handles failures, updates bindings or takes several steps.
- Inside a function, call a function parameter only where no secret condition decides the call (U4002).
- A function with an `edit` or `take` parameter cannot be used as a value (U2021).

## 4.7 Recursion and the entry point

- Direct and mutual recursion are allowed. There is no tail-call guarantee, and exhausting the call depth or the stack is runtime diagnostic U6003. Loops (§5.5) do not count toward the call depth.
- The entry point is `pub main() -> Unit` in the module set as `entry` in `una.toml`. It can declare `uses` over host capabilities (§7.7) and a `fails` clause.
- If `main` fails, the runtime prints the variant name and exits with code 1. Payload fields are printed only if they are `public`.

---


## Constructs

- [requires](https://una-lang.org/en/docs/language/functions/requires.md)
- [ensures](https://una-lang.org/en/docs/language/functions/ensures.md)
