Captain / Documentation / Part 3. The language

Blocks and control

Contents ↓

Captain has no if statement, no while keyword and no for. Choices and loops are written as keyword calls that take blocks: ifTrue:, whileTrue:, forEach:, the Option and Result combinators, and the operations that build one value from a list, such as collect:. This chapter explains what a block is, what each control form does, when a block gives a value, and why Captain's blocks are more limited than closures in other languages.

Blocks

A block is code in square brackets, optionally starting with parameters:

Fragment
[ :line | count := count + 1 ]

That block would be the argument of a forEach: inside a procedure. Each parameter is written :name; the | after the parameters is optional but usual. Inside, statements are separated by ., and the last . is optional. A block's statements are the same as a procedure body's: ret, assignment, and expressions.

The number of parameters is fixed by the call that receives the block: forEach: passes one item, ifOk: one value, ifTrue: nothing. Declaring a different number is CAP-TYPE-010.

Where the call that runs a block wants a value from it, the block gives the value of its last statement, which must be an expression (DR-0037). A trailing . changes nothing. A block whose last statement is an assignment or a ret, or that is empty, gives no value; where one is wanted, that is CAP-TYPE-039. The statements before the last are ordinary statements.

Blocks are not values

A block can appear in exactly two places: as a keyword argument, and as the head of whileTrue:. It cannot be stored in a local, returned, passed through a variable, or kept in a field:

Refused by the checker: CAP-PARSE-BLOCKVALUE
module Example::Blocks.

export handler -> i32 [
  h := [ ret 1 ].
  ret 1.
].

This is enforced by the grammar itself (DR-0001, DR-0003): a block is not an expression, so there is no way to write one anywhere else. Every block runs, if it runs at all, while the call it was written in is running. It never outlives that call, so there are no closures that capture variables and run later.

Choosing

ifTrue:, ifFalse: and ifTrue:ifFalse: are methods of bool:

choose.capt
module Example::Choose.

export sign n: i32 -> Text [
  (n < 0) ifTrue: [ ret "negative" ].
  (n = 0) ifTrue: [ ret "zero" ].
  ret "positive".
].

export size n: i32 -> Text [
  label := "small".
  (n > 100) ifTrue: [ label := "large" ] ifFalse: [
    (n > 10) ifTrue: [ label := "medium" ].
  ].
  ret label.
].

Written as statements, as above, they choose what runs. Where their value is wanted (assigned, returned, passed or used in an expression), the two-branch form gives the chosen block's value:

pick.capt
module Example::Pick.

export pick flag: bool -> i32 [
  x := flag ifTrue: [ 1 ] ifFalse: [ 2 ].
  ret x * 10.
].

export size n: i32 -> Text [
  ret (n > 100) ifTrue: [ "large" ] ifFalse: [
    (n > 10) ifTrue: [ "medium" ] ifFalse: [ "small" ]
  ].
].

export half n: i32 -> Text [
  h := ((n / 2) * 2 = n) ifTrue: [ n / 2 ] ifFalse: [ ret "odd" ].
  ret Text from: h.
].
Terminal
$ captain build pick.capt -o pick.capb
built pick.capb ([..] bytes, sha256 [..])
$ captain run pick.capb pick flag=false
run log: pick.runlog
20
$ captain run pick.capb size n=50
run log: size.runlog
"medium"
$ captain run pick.capb half n=8
run log: half.runlog
"4"
$ captain run pick.capb half n=7
run log: half.runlog
"odd"

Both blocks give the same type, exactly: there is no common type and no conversion (CAP-TYPE-040). One block may instead end in ret, as in half: it never gives a value, so the other's type is the form's. A literal in the second block is read as the first block's type, so flag ifTrue: [ big ] ifFalse: [ 0 ] with an i64 big is an i64.

Refused by the checker: CAP-TYPE-040
module Example::Choose.

export pick flag: bool -> i32 [
  x := flag ifTrue: [ 1 ] ifFalse: [ "two" ].
  ret 0.
].

A one-branch ifTrue: or ifFalse: gives nothing, because when its condition is false there is nothing to give. Using one as a value is CAP-TYPE-043, with the two-branch form as its help:

Refused by the checker: CAP-TYPE-043
module Example::Choose.

export pick flag: bool -> i32 [
  x := flag ifTrue: [ 1 ].
  ret x.
].

ifSome:ifNone: and ifOk:ifFail: give values by the same rule (Option and Result). The blocks of a choice may assign outer locals and perform effects whether or not the choice gives a value: they are control, not calculation.

The receiver must be a bool. There is no truthiness: count ifTrue: on an integer is refused, because i32 has no method ifTrue:.

ifFalse:ifTrue: (the other order) does not exist; write ifTrue:ifFalse:.

Looping

whileTrue: runs its argument block as long as its head block ends in true. The head block's last statement is the condition, and it must be a bool (CAP-TYPE-010):

loop.capt
module Example::Loop.

export countdown from: i32 -> Text [
  i := from.
  out := List empty: Text.
  [ i > 0 ] whileTrue: [
    out := out push: (Text from: i).
    i := i - 1.
  ].
  ret out join: " ".
].

export firstSquareAtLeast n: i32 -> i32 [
  i := 0.
  [ i * i < n ] whileTrue: [ i := i + 1 ].
  ret i.
].

The head block's last statement is the condition, a bool expression. It is evaluated before every round, including the first.

There is no counted loop (to:do: or timesRepeat:): keep a counter, as countdown does.

forEach: runs its block once for each item of a list, in order, with the item as the block's parameter. Lists and shapes has examples. Loops give no value: x := xs forEach: [ … ] is CAP-TYPE-043. To build a list from a list, use collect:, select: or reject:; to fold one into a value, inject:into:; to find an item, detect: (Building lists from lists).

Terminal
$ captain build loop.capt -o loop.capb
built loop.capb ([..] bytes, sha256 [..])
$ captain run loop.capb countdown from=3
run log: countdown.runlog
"3 2 1"
$ captain run loop.capb firstSquareAtLeast n=10
run log: firstSquareAtLeast.runlog
4

Leaving early

ret inside a block returns from the procedure, not just the block. That makes it the way to stop a loop as soon as the answer is known:

early.capt
module Example::Early.

export firstLong words: Text -> Text [
  (words splitOn: " ") forEach: [ :w |
    ((w size) > 4) ifTrue: [ ret w ].
  ].
  ret "".
].
Terminal
$ captain build early.capt -o early.capb
built early.capb ([..] bytes, sha256 [..])
$ captain run early.capb firstLong words="a quick brown fox"
run log: firstLong.runlog
"quick"

There is no break, no continue and no exception. To skip an item, put the rest of the block inside an ifTrue: or ifFalse:. To stop a loop without leaving the procedure, use whileTrue: with a flag or a counter in its condition. To find the first item that matches, detect: is shorter: ((words splitOn: " ") detect: [ :w | (w size) > 4 ]) gives an Option.

ret always means the procedure. So it is refused inside the blocks of collect: and its family (CAP-TYPE-041): their blocks give their last expression, and an exit hidden in a calculation is the kind of thing a reader misses.

Refused by the checker: CAP-TYPE-041
module Example::Early.

export firstLong words: Text -> Text [
  found := (words splitOn: " ") collect: [ :w |
    ((w size) > 4) ifTrue: [ ret w ].
    w
  ].
  ret "".
].

Blocks and the names around them

A block can read and assign the locals and parameters of the body it is written in. Names it declares itself, and its parameters, end with the block. A block parameter may not reuse a name that is already in scope (CAP-RESOLVE-007); see Modules and names.

Three kinds of block are stricter, because their code runs as a separate unit rather than in place:

  • the block of a frontier form, on host: server using: #Ssh do: [ ... ], runs on another machine. It may read outer values that can travel, but it may not assign them (Frontiers);
  • the block of xs parallelDo: [ :x | ... ] runs once per item as its own unit. It may read outer locals but not assign them (Text, lists and logic);
  • the blocks of collect:, select:, reject:, detect:, inject:into: and sortedBy: are pure: they may read outer locals but not assign them (CAP-TYPE-042), they cannot ret, and they perform no effects. An effect over a list is a forEach:.

Everywhere else a block shares the locals around it: an assignment inside it changes the local itself, and the block reads a local as it is when the block runs.

Why blocks work this way

Blocks that are not values, and blocks that give their last expression, come from Zing, the language Captain is a dialect of, and Captain keeps them for its own reasons.

A reader can see every block's whole life. A block runs inside the call it is written in, or not at all. No code runs later from a stored closure, on a path the reader cannot see from where the block is written. That is what lets the checker, captain plan and a reviewer account for every effect a program can perform, and it is what lets a frontier block be compiled to run on another machine: it is staged at compile time, never captured at run time (DR-0006).

Calculations and effects look different. A block that gives a value gives it from its last expression, the way Zing's closures do; ret keeps one meaning, the procedure. The blocks of collect: and its family are pure, so a reader finds effects in statements, forEach: and parallelDo: bodies, and calculations in collect:. That is also what lets captain plan go past a collect: over a list it will only know at run time, where a forEach: over the same list stops the plan (Plans and approval).

One way to write each thing, mostly. The old forms stay legal: a list can still be built with forEach: and push:, and a value chosen with an early ret. New code should use collect:, select: and a conditional that gives a value: they say what they compute, in one expression. What Captain leaves out, and why collects the absences that remain.