Captain / Documentation / Part 3. The language

Option and Result

Contents ↓

Captain has no null and no exceptions. A value that may be absent is an Option, and an operation that may fail returns a Result. Both are ordinary enums that every program has, and the checker makes the program handle each case before it can use the value inside.

The two enums

Fragment
enum Option[T] [ Some(v: T). None. ].
enum Result[T] [ Ok(v: T). Fail(err: Err). ].
struct Err { kind: Symbol, message: Text }.

That is how the compiler declares them; a program uses them without a use. Every failure carries an Err: a kind, a stable symbol that programs test, and a message for people.

Making them

They are built like any enum variant:

Written Gives
Some { v: x } an Option holding x
None an empty Option
Ok { v: x } a successful Result holding x
Fail { err: Err { kind: #Name, message: "..." } } a failed Result

The type argument comes from the context, usually the procedure's declared result. None on its own, with nothing to say what it would hold, is refused (CAP-TYPE-018).

find.capt
module Example::Find.

export position name: Text -> Option[i32] [
  i := 0.
  #( "ada", "bob", "cy" ) forEach: [ :each |
    (each = name) ifTrue: [ ret Some { v: i } ].
    i := i + 1.
  ].
  ret None.
].

export positive t: Text -> Result[i32] [
  n := 0.
  (Int parse: t)
    ifOk: [ :v | n := v ]
    ifFail: [ :e | ret Fail { err: e } ].
  (n <= 0) ifTrue: [
    ret Fail { err: Err { kind: #NotPositive, message: "must be above zero" } }.
  ].
  ret Ok { v: n }.
].

Taking them apart

An Option or Result is taken apart with a combinator: a method that runs one of its blocks, depending on the variant, and binds the payload to the block's parameter.

Written Runs
o ifSome: [ :v \| ... ] ifNone: [ ... ] one of the two blocks
r ifOk: [ :v \| ... ] ifFail: [ :e \| ... ] one of the two blocks
r ifOk: [ :v \| ... ] the block if r is Ok
r ifFail: [ :e \| ... ] the block if r is Fail; e is an Err

There is no way to reach the v inside without one of these: no (o value), no unchecked unwrap. The block that has the value is the only place the value exists.

A program gets a value out in one of three ways.

Use the two-block form as a value. Like ifTrue:ifFalse:, where its value is wanted ifSome:ifNone: or ifOk:ifFail: gives the value of the block that ran (DR-0037). Both blocks give the same type, or one ends in ret:

values.capt
module Example::Values.

export greet who: Text -> Text [
  found := #( "ada", "bob" ) detect: [ :each | each = who ].
  ret found ifSome: [ :name | "hello " append: name ] ifNone: [ "nobody" ].
].

export port t: Text -> i32 [
  p := (Int parse: t) ifOk: [ :v | v ] ifFail: [ :e | ret 0 ].
  ret p + 8000.
].
Terminal
$ captain build values.capt -o values.capb
built values.capb ([..] bytes, sha256 [..])
$ captain run values.capb greet who=bob
run log: greet.runlog
"hello bob"
$ captain run values.capb greet who=dan
run log: greet.runlog
"nobody"
$ captain run values.capb port t=80
run log: port.runlog
8080
$ captain run values.capb port t=eighty
run log: port.runlog
0

A one-block form, r ifOk: [ … ] or r ifFail: [ … ], gives nothing: when it does not run there is nothing to give, and assigning one is CAP-TYPE-043. Written as statements, the combinators choose what runs, as below.

Return from inside the blocks. ret in a block returns from the whole procedure, so each branch can return its own answer. When every branch returns, nothing more is needed after the statement:

describe.capt
module Example::Describe.

use Example::Find.

export where name: Text -> Text [
  (Find::position name: name)
    ifSome: [ :i | ret "at " append: (Text from: i) ]
    ifNone: [ ret "absent" ].
].

Assign an outer local. A block can assign a local declared before it, as positive above does with n. Declare the local with a default first, so it has a value on every path.

The early-return pattern

Most code that can fail has the same shape: try a step, stop with the failure if it failed, and go on with the value if it didn't. In Captain that is a combinator whose ifFail: block returns the failure:

Fragment
(Int parse: t)
  ifOk: [ :v | n := v ]
  ifFail: [ :e | ret Fail { err: e } ].

That is the middle of positive above. The failure goes back to the caller unchanged, with its kind and message, and the code after the statement runs only on success. A caller that wants a different failure builds its own Err, keeping the original's kind or choosing a new one.

(e kind) is the symbol to test, and (e message) the text to show:

kinds.capt
module Example::Kinds.

export kindOf t: Text -> Symbol [
  (Int parse: t) ifFail: [ :e | ret (e kind) ].
  ret #Fine.
].
Terminal
$ captain check find.capt describe.capt
ok    find.capt (module Example::Find, 2 declarations)
ok    describe.capt (module Example::Describe, 1 declaration)
checked 2 files as 2 modules, no errors
$ captain build find.capt -o find.capb
built find.capb ([..] bytes, sha256 [..])
$ captain run find.capb position name=bob
run log: position.runlog
Some { v: 1 }
$ captain run find.capb position name=dan
run log: position.runlog
None
$ captain run find.capb positive t=5
run log: positive.runlog
Ok { v: 5 }
$ captain run find.capb positive t=-5
run log: positive.runlog
Fail { err: Err { kind: #NotPositive, message: "must be above zero" } }
$ captain run find.capb positive t=five
run log: positive.runlog
Fail { err: Err { kind: #IntParseError, message: "`five` is not an i32" } }
$ captain build kinds.capt -o kinds.capb
built kinds.capb ([..] bytes, sha256 [..])
$ captain run kinds.capb kindOf t=x
run log: kindOf.runlog
#IntParseError

No null

A value of a type other than Option is always present. A Text parameter always holds a text, and a struct's Text field always has one. Code never checks for null, because there is none to check for.

Smalltalk's and other languages' words for null are answered with the Captain way:

Refused by the checker: CAP-RESOLVE-008
module Example::Absent.

export missing o: Option[i32] -> bool [
  ret (o isNil).
].

The help line says Captain has no nil: a value that may be absent is an Option, taken apart with ifSome:ifNone:.

An Option field in a struct is how data says a field may be absent. When JSON is decoded into such a struct, a missing key or a null becomes None (JSON and number text).

Why failures are values

A failure in Captain is a value that the program must look at, not an exception that unwinds past code that never mentioned it. Each Result in a procedure's signature says it can fail, each ifFail: says what happens then, and the kind of each failure is a symbol that can be tested and recorded. A reviewer reading a program sees every path a failure can take.

A fault is different: integer overflow, a list index out of range, or an inexact division stops the run with a CAP-RUN-* code. Faults are bugs in the program, not conditions to handle, so they are not Results.