Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Errors: Option, Result, and ?

Lingua Tungga has no exceptions. Expected failure is a value: Option<T> for absence and Result<T, E> for a reason.

Option

export fn find(c: Catalog, title: Str) -> Option<Book> {
  c.books.filter(fn(b) => b.title == title).get(0)
}

Option methods: is_some(), is_none(), unwrap(), unwrap_or(default), map(fn), and_then(fn).

unwrap() on None is a trap, not a recoverable error.

Result

export fn parse(text: Str) -> Result<Int, Str> {
  match text.parse_int() {
    Some(value) => Ok(value)
    None => Err("not a number")
  }
}

Result methods: is_ok(), is_err(), unwrap(), unwrap_or(default), map(fn), map_err(fn), and_then(fn).

The ? operator

expr? unwraps Ok/Some and returns the Err/None from the enclosing function.

export fn double(text: Str) -> Result<Int, Str> {
  let value = number(text)?
  Ok(value * 2)
}

Rules:

  • ? on Option<T> requires a function returning Option<U>.
  • ? on Result<T, E> requires a function returning Result<U, E>.
  • Option and Result cannot be mixed in one function.
  • ? is rejected inside a lambda: its return would leave the lambda, not the function.

Traps

Traps stop the program through the host language’s native mechanism. They are never used as normal flow:

  • integer division or remainder by zero;
  • unwrap() on None or Err;
  • unbounded recursion (the host stack limit is not part of the contract).

Out-of-bounds indexing does not trap: xs[i], m[k], d["k"], and s[i] return None.

What stays in the host

IO, async, concurrency, and HTTP are outside the language. A package returns values; the host decides what to do with them.

Complete example

package question {
  export fn number(text: Str) -> Result<Int, Str> {
    match text.parse_int() {
      Some(value) => Ok(value)
      None => Err("not a number")
    }
  }

  export fn double(text: Str) -> Result<Int, Str> {
    let value = number(text)?
    Ok(value * 2)
  }

  test "success" {
    expect.eq(double("21"), Ok(42))
  }

  test "propagates error" {
    expect.eq(double("x"), Err("not a number"))
  }
}