Errors: Result and Option

View source

Report failure and missing values with Result and Option, match on them with case, and pass errors up with the question mark.

Things go wrong in real programs. A number cannot be divided by zero. A value that you look for is not there. Actus has no hidden exceptions. Instead, a verb says in its return type that it can fail, and the caller has to deal with that. Two types are built in for this: Result and Option.

  • Result[T, E] is either Ok with a value of type T, or Err with an error of type E. Use it when something can fail and you want to say why.
  • Option[T] is either Some with a value of type T, or None. Use it when a value may be absent. There is no null in Actus.

Both are enums, like the ones in Structs, enums and case, and you take them apart with case.

Return a Result

The verb divide below can fail, so it returns Result[Int, DivideError]. A success is Ok with the answer. A failure is Err with a variant of our own DivideError enum:

actus
enum DivideError {
    ByZero,
}

verb main() {
    erg top = 20;
    erg good = 4;
    erg zero = 0;
    erg first = divide(top: abs top, bottom: abs good);
    erg second = divide(top: abs top, bottom: abs zero);
    case dat first {
        Result.Ok(value) => println(int: value),
        Result.Err(_) => println(string: "cannot divide"),
    };
    case dat second {
        Result.Ok(value) => println(int: value),
        Result.Err(_) => println(string: "cannot divide"),
    };
}

verb divide(abs top: Int, abs bottom: Int) -> Result[Int, DivideError] {
    if bottom == 0 {
        return Result[Int, DivideError].Err(DivideError.ByZero);
    }
    return Result[Int, DivideError].Ok(top / bottom);
}
bash
actus run
text
5
cannot divide
process exited with status 0

In divide, the result is built with the full type name, Result[Int, DivideError].Err(...). In main, case dat first looks inside the result. The arm Result.Ok(value) names the answer, and the arm Result.Err(_) handles the failure. The _ means "there is an error, and I do not need its details here".

case dat first uses up first. The case takes the value, and you cannot use first again afterwards. The end of this page shows how to look at a value without using it up.

Because a case must cover every variant, you cannot forget the failure. The compiler rejects a case without the Err arm, as the next section shows for Option.

Return an Option

When there is no error to explain and a value is simply missing, use Option. This verb gives back the first even number of two:

actus
verb main() {
    erg three = 3;
    erg five = 5;
    erg eight = 8;
    erg found = first_even(a: abs three, b: abs eight);
    erg missing = first_even(a: abs three, b: abs five);
    case dat found {
        Option.Some(n) => println(int: n),
        Option.None => println(string: "no even number"),
    };
    case dat missing {
        Option.Some(n) => println(int: n),
        Option.None => println(string: "no even number"),
    };
}

verb first_even(abs a: Int, abs b: Int) -> Option[Int] {
    if a % 2 == 0 {
        return Option[Int].Some(a);
    }
    if b % 2 == 0 {
        return Option[Int].Some(b);
    }
    return Option[Int].None;
}
bash
actus run
text
8
no even number
process exited with status 0

Some(n) carries the number, and None carries nothing. As with Result, the case has to handle both:

actus
verb main() {
    erg three = 3;
    erg found = first_even(a: abs three);
    case dat found {
        Option.Some(n) => println(int: n),
    };
}

verb first_even(abs a: Int) -> Option[Int] {
    if a % 2 == 0 {
        return Option[Int].Some(a);
    }
    return Option[Int].None;
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1045] at 4:5: non-exhaustive match on `Option`; missing: None

You also cannot use an Option[Int] as if it were an Int. The value may be missing, so you must go through case:

actus
verb main() {
    erg two = 2;
    erg found = first_even(a: abs two);
    erg n: Int = found;
    println(int: n);
}

verb first_even(abs a: Int) -> Option[Int] {
    if a % 2 == 0 {
        return Option[Int].Some(a);
    }
    return Option[Int].None;
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1027] at 4:5: type mismatch for `n`: expected `Int`, found `Option[Int]`

Pass errors up with the question mark

Often a verb cannot do anything useful with an error and only wants to pass it to its caller. Put ? after a call that returns a Result. If the result is Ok, you get the value. If it is Err, the verb returns that error right away.

actus
enum DivideError {
    ByZero,
}

verb main() {
    erg top = 20;
    erg five = 5;
    erg zero = 0;
    report(top: abs top, bottom: abs five);
    report(top: abs top, bottom: abs zero);
}

verb report(abs top: Int, abs bottom: Int) {
    erg result = half_of_quotient(top: abs top, bottom: abs bottom);
    case dat result {
        Result.Ok(value) => println(int: value),
        Result.Err(error) => case dat error {
            DivideError.ByZero => println(string: "division by zero"),
        },
    };
}

verb half_of_quotient(abs top: Int, abs bottom: Int) -> Result[Int, DivideError] {
    erg quotient = divide(top: abs top, bottom: abs bottom)?;
    return Ok(quotient / 2);
}

verb divide(abs top: Int, abs bottom: Int) -> Result[Int, DivideError] {
    if bottom == 0 {
        return Err(DivideError.ByZero);
    }
    return Ok(top / bottom);
}
bash
actus run
text
2
division by zero
process exited with status 0

In half_of_quotient, the line erg quotient = divide(...)?; gives the answer when divide succeeds. When divide fails, half_of_quotient stops and returns the same Err, so the second report prints division by zero. Inside a verb whose return type is a Result, you can also write Ok(...) and Err(...) without the type.

You can also write ? inside a larger expression, for example in the condition of an if. If the call fails, the verb returns the error at that point:

actus
enum DivideError {
    ByZero,
}

verb main() {
    erg top = 20;
    erg five = 5;
    erg zero = 0;
    report(top: abs top, bottom: abs five);
    report(top: abs top, bottom: abs zero);
}

verb report(abs top: Int, abs bottom: Int) {
    erg result = describe(top: abs top, bottom: abs bottom);
    case dat result {
        Result.Ok(flag) => println(int: flag),
        Result.Err(_) => println(string: "division by zero"),
    };
}

verb describe(abs top: Int, abs bottom: Int) -> Result[Int, DivideError] {
    if divide(top: abs top, bottom: abs bottom)? > 3 {
        return Ok(1);
    }
    return Ok(0);
}

verb divide(abs top: Int, abs bottom: Int) -> Result[Int, DivideError] {
    if bottom == 0 {
        return Err(DivideError.ByZero);
    }
    return Ok(top / bottom);
}
bash
actus run
text
1
division by zero
process exited with status 0

The ? has two conditions. The verb that uses it must return a Result, and the error types must be the same.

actus
verb main() {
    erg one = 1;
    erg value = check(n: abs one)?;
    println(int: value);
}

verb check(abs n: Int) -> Result[Int, Int] {
    return Ok(n);
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1025] at 3:17: type mismatch for `return type` in `?`: expected `Result[T, E]`, found `no return type`
actus
enum ParseError {
    Empty,
}

verb main() {
    erg one = 1;
    drop(second(n: abs one));
}

verb first(abs n: Int) -> Result[Int, ParseError] {
    return Ok(n);
}

verb second(abs n: Int) -> Result[Int, Int] {
    erg value = first(n: abs n)?;
    return Ok(value);
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1025] at 15:17: type mismatch for `Result` in `?`: expected `Result[Int,Int]`, found `Result[Int,ParseError]`

In the second program, first fails with a ParseError and second can only fail with an Int. Actus does not convert one error type into the other for you.

A result is never thrown away

A Result carries an error, and an Option may hold no value. So Actus does not let you ignore either one. A call that returns a Result or an Option must be used: bind it and look at it, return it, pass it on, or propagate it with ?. If you call it as a statement on its own, the compiler stops you with E1120:

actus
verb main() {
    erg two = 2;
    first_even(a: abs two);
}

verb first_even(abs a: Int) -> Option[Int] {
    if a % 2 == 0 {
        return Option[Int].Some(a);
    }
    return Option[Int].None;
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1120] at 3:5: must-use `Option` from `first_even` was ignored: an `Option` may hold no value, which must be handled

The same error appears when you bind the value and then never use the binding. It is the same mistake: the value was never looked at. The message names the binding.

actus
verb main() {
    erg two = 2;
    erg found = first_even(a: abs two);
}

verb first_even(abs a: Int) -> Option[Int] {
    if a % 2 == 0 {
        return Option[Int].Some(a);
    }
    return Option[Int].None;
}
text
/home/you/hello/src/main.act: error[E1120] at 3:5: binding `found` holds a must-use `Option` from `first_even` and is never used: an `Option` may hold no value, which must be handled

There are three ways out. Look at the value with case, as you did above. Pass the error up with ? when the verb returns a Result with the same error type. Or, when you really do not care about the outcome, say so with drop:

actus
verb main() {
    erg two = 2;
    drop(first_even(a: abs two));
    println(string: "the outcome was dropped on purpose");
}

verb first_even(abs a: Int) -> Option[Int] {
    if a % 2 == 0 {
        return Option[Int].Some(a);
    }
    return Option[Int].None;
}
bash
actus run
text
the outcome was dropped on purpose
process exited with status 0

drop(first_even(...)); is the explicit discard. It ends the value on purpose, and it shows the reader that the choice was made. A ? on a call statement, such as first(n: abs n)?;, also counts as using the result, because the error goes to the caller.

Looking without using it up

case dat consumes the value, so a second case on the same variable is an error:

actus
verb main() {
    erg two = 2;
    erg found = first_even(a: abs two);
    case dat found {
        Option.Some(n) => println(int: n),
        Option.None => println(string: "none"),
    };
    case dat found {
        Option.Some(n) => println(int: n),
        Option.None => println(string: "none"),
    };
}

verb first_even(abs a: Int) -> Option[Int] {
    if a % 2 == 0 {
        return Option[Int].Some(a);
    }
    return Option[Int].None;
}
bash
actus check
text
/home/you/hello/src/main.act: error[E1005] at 8:14: use of moved binding `found`

When you want to look at a value more than once, use case abs. It reads the value and leaves it where it is:

actus
verb main() {
    erg two = 2;
    erg found = first_even(a: abs two);
    case abs found {
        Option.Some(n) => println(int: n),
        Option.None => println(string: "none"),
    };
    case abs found {
        Option.Some(n) => println(int: n),
        Option.None => println(string: "none"),
    };
}

verb first_even(abs a: Int) -> Option[Int] {
    if a % 2 == 0 {
        return Option[Int].Some(a);
    }
    return Option[Int].None;
}
bash
actus run
text
2
2
process exited with status 0

Errors and the exit status

main cannot return a Result. It returns nothing or an Int, so you deal with errors inside main, and then choose the exit status:

actus
verb main() -> Result[Int, Int] {
    return Ok(0);
}
bash
actus run
text
error: hosted entry verb `main` must return nothing or an integer exit status, found `Result[Int, Int]`; return an `Int` and handle errors inside `main`

For example, report the failure on the error stream and return a status that is not 0. The error stream, eprintln, is described in Printing and input/output.

actus
verb main() -> Int {
    erg top = 20;
    erg zero = 0;
    erg result = divide(top: abs top, bottom: abs zero);
    return case dat result {
        Result.Ok(_) => 0,
        Result.Err(_) => {
            eprintln(string: "division failed");
            return 1;
        },
    };
}

verb divide(abs top: Int, abs bottom: Int) -> Result[Int, Int] {
    if bottom == 0 {
        return Err(1);
    }
    return Ok(top / bottom);
}
bash
actus run
text
division failed
process exited with status 1

What you learned

  • Result[T, E] is Ok(value) or Err(error). Option[T] is Some(value) or None.
  • A verb that can fail says so in its return type.
  • case takes the value apart and must cover both variants. Use case dat to use it up, case abs to look at it.
  • ? returns the error of a failed call to the caller. The verb must return a Result with the same error type.
  • A Result or an Option is never thrown away. Look at it, return it, propagate it with ?, or end it on purpose with drop(...). Otherwise the compiler reports E1120.
  • main returns nothing or an Int. Handle errors in main and return a status.

Next: Printing and input/output.