These operations are in every program. They are pure: they run the same way
in check, plan, run and replay, they never appear in a plan as effects,
and they cost one VM instruction each (octets operations cost more; see
Octets and digests).
Two spelling rules apply throughout. A member has no colon and is read in
parentheses: (t size), (xs count). A method takes keyword arguments:
t contains: "x". And because Captain looks like Smalltalk, the checker
answers a Smalltalk word it does not know with the Captain one: xs do: gets
"Captain spells it forEach:", (xs size) gets "a list's length is
(xs count)".
Text
Text is a string of Unicode scalar values, held as UTF-8.
| Written | Gives | Notes |
|---|---|---|
(t size) |
i32 |
length in characters (Unicode scalars), not bytes |
(t isEmpty) |
bool |
|
(t trimmed) |
Text |
leading and trailing Unicode white space removed |
(t lines) |
List[Text] |
split on \n; a \r before it is dropped; a final newline does not add an empty last line |
(t characters) |
List[Text] |
one item per Unicode scalar, in order; not grapheme clusters. VM 6 |
t splitOn: sep |
List[Text] |
every piece, empty ones included; an empty sep gives #( t ) |
t contains: s |
bool |
|
t startsWith: s, t endsWith: s |
bool |
|
t occurrencesOf: s |
i32 |
non-overlapping, left to right; an empty s occurs nowhere |
t replace: s with: r |
Text |
every occurrence |
t replaceOnce: s with: r |
Result[Text] |
fails (#ReplaceOnceError) unless s occurs exactly once |
a append: b |
Text |
Captain has no + or , on text |
a = b, a != b |
bool |
|
a < b, <=, >, >= |
bool |
Unicode code point order, which is also UTF-8 byte order. VM 4 |
All of these except splitOn: and = need VM 3 or later.
replaceOnce:with: exists because editing a file by replacing one exact
passage is the common case, and a passage that appears twice, or not at all,
almost always means the edit is aimed at the wrong place. It makes that a
failure you handle instead of a silent change.
Lists
List[T] is an immutable sequence. Operations that "change" a list return a
new one, and the checker refuses a statement that throws that result away
(CAP-TYPE-030), because names push: x. on its own does nothing.
| Written | Gives | Notes |
|---|---|---|
List empty: T |
List[T] |
T is any type, including i32, i64, bool |
#( a, b, c ) |
List[T] |
a shape of unlabelled items that starts with a literal is a list of that literal's type |
(xs count) |
i32 |
|
(xs isEmpty) |
bool |
VM 3 |
xs at: i |
T |
zero-based; out of range is a run-time fault (CAP-RUN-LIST) |
xs push: x |
List[T] |
x added at the end |
xs at: i put: x |
List[T] |
a new list with item i replaced. VM 3 |
xs includes: x |
bool |
VM 3 |
xs join: sep |
Text |
for List[Text] only. VM 3 |
(xs sorted) |
List[T] |
for lists of Text, i32 or i64; text sorts by code point. VM 3 |
(xs distinct) |
List[T] |
first occurrence of each kept; for Text, integers, bool or symbols. VM 3 |
xs collect: [ :x \| e ] |
List[U] |
each block value, in order; U is the type of the block's last expression |
xs select: [ :x \| p ] |
List[T] |
the items where the block gives true |
xs reject: [ :x \| p ] |
List[T] |
the items where it gives false |
xs detect: [ :x \| p ] |
Option[T] |
the first item where it gives true, or None; no block runs after the first match |
xs inject: a into: [ :acc :x \| e ] |
U, the type of a |
folded left: the block gives the next accumulator; an empty list gives a |
xs sortedBy: [ :x \| k ] |
List[T] |
ascending by the key, stable; the key's type is one < orders. VM 8 |
xs forEach: [ :x \| ... ] |
nothing | a statement; ret inside the block returns from the procedure |
xs parallelDo: [ :x \| ... ] |
nothing | explicit fan-out: the block runs once per item as a staged unit that may read outer variables but not assign them; outcomes and failures are taken in input order, never completion order (today's executor runs the items one after another) |
The blocks of collect: and the rest of its family give their last
expression, and they are pure: they may read outer locals but not assign
them, they cannot ret, and they perform no effects (DR-0037). Effects over a
list are a forEach:. Written as a statement, a collection operation does
nothing and is refused (CAP-TYPE-030). The checker answers the other
languages' words with these: map: gets collect:, filter: gets
select:, detect:ifNone: and find: get detect:, reduce: and fold:
get inject:into:, and sort: [ :a :b | … ] gets sortedBy:, which takes a
key and never a comparator. Lists and
shapes has
examples, and Blocks and control
the rules.
bool
| Written | Gives | Notes |
|---|---|---|
(b not) |
bool |
VM 3 |
a & b, a and: b |
bool |
b is evaluated only if a is true |
a \| b, a or: b |
bool |
b is evaluated only if a is false |
b ifTrue: [ ... ] |
nothing | |
b ifFalse: [ ... ] |
nothing | |
b ifTrue: [ ... ] ifFalse: [ ... ] |
the chosen block's value, or nothing | gives a value where one is wanted: both blocks give one type, or one ends in ret |
and: and or: take an expression, not a block: the argument is already
evaluated only when it decides the answer.
Option and Result
enum Option[T] [ Some(v: T). None. ].
enum Result[T] [ Ok(v: T). Fail(err: Err). ].Those are the prelude's two enums, as the compiler declares them (Err is on
the next page). They are taken apart
with combinators whose blocks bind the payload:
| Written | Runs |
|---|---|
o ifSome: [ :v \| ... ] ifNone: [ ... ] |
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 |
r ifOk: [ :v \| ... ] ifFail: [ :e \| ... ] |
one of the two blocks |
The two-block forms give the chosen block's value where a value is wanted,
by the rule of ifTrue:ifFalse:: who := found ifSome: [ :v | v ] ifNone: [
"nobody" ]. The one-block forms give nothing. Either way, ret inside a
block returns from the procedure, and a procedure whose every branch returns
needs no ret after them.
Conversions
Captain converts in three ways, and each says what it can do:
| Written | Gives | Notes |
|---|---|---|
n as: T |
T |
exact numeric conversion: i32 to i64, i32 or i64 to Decimal (at scale 0), or a type to itself. It cannot fail, so only conversions that lose nothing exist; any other, such as i64 to i32 or Decimal to an integer, is refused when the program is checked (CAP-TYPE-033). VM 7, except a type to itself, which compiles to nothing |
T parse: t |
Result[T] |
text to a value, which can fail: Int parse: t gives Result[i32] (surrounding white space ignored; fails with #IntParseError), and each tagged type has its own parse: (next page) |
Text from: x |
Text |
formatting: x is an integer, Decimal, Text, symbol (written without #), quantity (8GiB, 90s, 12.50USD) or tagged value ("/etc"#path gives /etc; a Digest gives lowercase hex) |
There is no i64 parse and no decimal parse in the prelude. For JSON numbers,
decode into a struct field of the type you need
(JSON and number text). The checker points
Smalltalk habits at these: asDecimal gets "write (n as: Decimal)",
printString gets "write Text from: value", and as: on text gets "text
becomes a number with Int parse: text, which is a Result".
Example
module Example::Words.
;; Distinct words of a line, sorted.
export vocabulary line: Text -> Text [
words := ((line trimmed) splitOn: " ") reject: [ :w | (w isEmpty) ].
ret ((words sorted) distinct) join: ", ".
].
;; Rename one setting, refusing if the old name is not there exactly once.
export rename config: Text -> Result[Text] [
ret config replaceOnce: "timeout=" with: "deadline=".
].
export total of: Text -> Result[i32] [
sum := 0.
(of splitOn: ",") forEach: [ :part |
(Int parse: part)
ifOk: [ :n | sum := sum + n ]
ifFail: [ :e | ret Fail { err: e } ].
].
ret Ok { v: sum }.
].$ captain build words.capt -o words.capb
built words.capb ([..] bytes, sha256 [..])
$ captain run words.capb vocabulary line=" the cat saw the dog "
run log: vocabulary.runlog
"cat, dog, saw, the"
$ captain run words.capb rename config="timeout=30"
run log: rename.runlog
Ok { v: "deadline=30" }
$ captain run words.capb rename config="timeout=30 timeout=40"
run log: rename.runlog
Fail { err: Err { kind: #ReplaceOnceError, message: "the passage must appear exactly once, and it appears 2 times" } }
$ captain run words.capb total of="1, 2, 39"
run log: total.runlog
Ok { v: 42 }
$ captain run words.capb total of="1,two"
run log: total.runlog
Fail { err: Err { kind: #IntParseError, message: "`two` is not an i32" } }Throwing away a computed list is refused before anything runs:
module Example::Lost.
export names -> List[Text] [
names := List empty: Text.
names push: "ada".
ret names.
].