Captain / Documentation / Part 3. The language

Lists and shapes

Contents ↓

List[T] is Captain's one collection: an ordered sequence of values of one type. A shape, #( ... ), is how lists and records are written inline. This chapter explains how lists behave and what a shape can stand for. The full list of operations is in Text, lists and logic.

Lists are values

A list never changes. Every operation that "changes" one gives a new list and leaves the old one as it was:

Written Gives
List empty: T an empty List[T]
xs push: x a new list, x added at the end
xs at: i put: x a new list, item i replaced
xs at: i item i, counting from 0
(xs count) the number of items
(xs isEmpty) whether there are none
xs includes: x whether x is an item
xs join: sep a List[Text] joined into one text
(xs sorted) a new list in order
(xs distinct) a new list, each item once
xs collect: [ :x \| e ] a new list of the block's values
xs select: [ :x \| p ] a new list of the items where p is true
xs reject: [ :x \| p ] a new list of the items where p is false
xs detect: [ :x \| p ] the first item where p is true, as an Option
xs inject: a into: [ :acc :x \| e ] a folded through the items
xs sortedBy: [ :x \| k ] a new list in order of the key k, stable
xs forEach: [ :x \| ... ] runs the block for each item, in order

Since push: gives a new list, a program that grows a list keeps the result each time:

lists.capt
module Example::Lists.

export evens upTo: i32 -> List[i32] [
  out := List empty: i32.
  i := 0.
  [ i <= upTo ] whileTrue: [
    out := out push: i.
    i := i + 2.
  ].
  ret out.
].

export sum upTo: i32 -> i32 [
  total := 0.
  (evens upTo: upTo) forEach: [ :n | total := total + n ].
  ret total.
].

export tidy -> Text [
  ret (#( "pear", "fig", "pear", "apple" ) distinct sorted) join: ", ".
].

export second -> i32 [
  ret #( 2, 3, 5, 7 ) at: 1.
].

export item i: i32 -> i32 [
  ret #( 2, 3, 5, 7 ) at: i.
].

Forgetting to keep it is refused, CAP-TYPE-030, because the statement would do nothing:

Refused by the checker: CAP-TYPE-030
module Example::Lists.

export names -> List[Text] [
  names := List empty: Text.
  names push: "ada".
  ret names.
].

xs at: i with an index outside the list is not a Result: it stops the run with CAP-RUN-LIST. An index out of range is a bug in the program, so it is a fault, like integer overflow. Check (xs count) first when an index comes from data.

Terminal
$ captain build lists.capt -o lists.capb
built lists.capb ([..] bytes, sha256 [..])
$ captain run lists.capb evens upTo=10
run log: evens.runlog
#( 0, 2, 4, 6, 8, 10 )
$ captain run lists.capb sum upTo=10
run log: sum.runlog
30
$ captain run lists.capb tidy
run log: tidy.runlog
"apple, fig, pear"
$ captain run lists.capb second
run log: second.runlog
3
$ captain run lists.capb item i=9
run log: item.runlog
error[CAP-RUN-LIST]: index 9 out of range (count 4)

sorted applies to lists of Text, i32 or i64, and distinct also to bool and symbols: the operations need an order or an equality the VM knows. A list of records is sorted by one of its fields with sortedBy:, below.

Building lists from lists

Six operations make a new value from a list by running a block on each item, in order (DR-0037). Their blocks give a value: the value of the block's last statement, which must be an expression.

collections.capt
module Example::Collections.

struct Job { name: Text, minutes: i32 }.

;; "backup=40" is a job; minutes that are not a number count as 0.
job entry: Text -> Job [
  parts := entry splitOn: "=".
  minutes := (Int parse: (parts at: 1)) ifOk: [ :m | m ] ifFail: [ :e | 0 ].
  ret Job { name: (parts at: 0), minutes: minutes }.
].

jobs queue: Text -> List[Job] [
  ret (queue splitOn: " ") collect: [ :entry | job entry: entry ].
].

export names queue: Text -> Text [
  ret ((jobs queue: queue) collect: [ :j | (j name) ]) join: ", ".
].

export long queue: Text over: i32 -> Text [
  kept := (jobs queue: queue) select: [ :j | (j minutes) > over ].
  ret (kept collect: [ :j | (j name) ]) join: ", ".
].

export short queue: Text over: i32 -> i32 [
  ret (((jobs queue: queue) reject: [ :j | (j minutes) > over ]) count).
].

export total queue: Text -> i32 [
  ret (jobs queue: queue) inject: 0 into: [ :sum :j | sum + (j minutes) ].
].

export first queue: Text over: i32 -> Text [
  found := (jobs queue: queue) detect: [ :j | (j minutes) > over ].
  ret found ifSome: [ :j | (j name) ] ifNone: [ "none" ].
].

export byLength queue: Text -> Text [
  ordered := (jobs queue: queue) sortedBy: [ :j | (j minutes) ].
  ret (ordered collect: [ :j | (j name) ]) join: ", ".
].
Terminal
$ captain build collections.capt -o collections.capb
built collections.capb ([..] bytes, sha256 [..])
$ captain run collections.capb names queue="backup=40 index=5 report=40 vacuum=15"
run log: names.runlog
"backup, index, report, vacuum"
$ captain run collections.capb long queue="backup=40 index=5 report=40 vacuum=15" over=10
run log: long.runlog
"backup, report, vacuum"
$ captain run collections.capb short queue="backup=40 index=5 report=40 vacuum=15" over=10
run log: short.runlog
1
$ captain run collections.capb total queue="backup=40 index=5 report=40 vacuum=15"
run log: total.runlog
100
$ captain run collections.capb first queue="backup=40 index=5 report=40 vacuum=15" over=20
run log: first.runlog
"backup"
$ captain run collections.capb first queue="backup=40 index=5" over=60
run log: first.runlog
"none"
$ captain run collections.capb byLength queue="backup=40 index=5 report=40 vacuum=15"
run log: byLength.runlog
"index, vacuum, backup, report"
  • collect: gives a list of the block's values; their type is the type of the block's last expression.
  • select: keeps the items whose block gives true, and reject: the ones whose block gives false.
  • detect: gives the first item whose block gives true, as an Option, and runs no block after it.
  • inject: a into: [ :acc :x | … ] starts from a, and each block gives the next accumulator, which must be of a's type. An empty list gives a.
  • sortedBy: sorts by a key the block computes once per item: an integer, a Decimal, Text, a quantity, an Instant or a Date, which < orders. Ties keep their order, so backup stays before report. It needs VM generation 8; the other five need nothing newer than the program already does.

These blocks are pure. They may read the locals around them but not assign them, ret cannot leave them, and they perform no effects: an effect over a list is a forEach:. That keeps calculations and effects apart for a reader, and lets captain plan look past a calculation over a list it will only know when the program runs (Plans and approval).

Refused by the checker: CAP-TYPE-042
module Example::Count.

export count text: Text -> i32 [
  n := 0.
  words := (text splitOn: " ") collect: [ :w | n := n + 1. w ].
  ret n.
].

The help says to carry a total with inject:into:. An effect in one of these blocks is refused too, with forEach: as the help:

Refused by the checker: CAP-EFFECT-032
module Example::Sizes.

export sizes dir: Path -> List[i32] [
  ret #( "a", "b" ) collect: [ :name |
    ((listDirectory path: dir maxEntries: 10) count)
  ].
].

Sorting takes a key, never a comparator: sort: [ :a :b | … ] gets sortedBy: as its help. A comparator's order depends on the algorithm unless it keeps laws the checker cannot prove; a stable sort by a key depends only on the keys. To sort by two keys, sort by the minor one first, then by the major one.

The checker answers the other languages' words with Captain's: map: gets collect:, filter: gets select:, reduce: gets inject:into:, (xs size) gets "a list's length is (xs count)", and xs do: gets "Captain spells it forEach:".

Shapes

A shape is a comma-separated list of items in #( ... ), each optionally labelled. A shape has no type of its own. It is checked against the type its context expects:

Expected type The shape must be
List[T] all positional; each item a T
a struct all labelled, with exactly the struct's fields
shapes.capt
module Example::Shapes.

export struct Point { x: i32, y: i32 }.

export corners -> List[Point] [
  ret #( #( x: 0, y: 0 ), #( x: 4, y: 3 ) ).
].

export nested -> List[List[i32]] [
  ret #( #( 1, 2 ), #( 3 ) ).
].

export none -> List[Text] [
  ret #().
].
Terminal
$ captain build shapes.capt -o shapes.capb
built shapes.capb ([..] bytes, sha256 [..])
$ captain run shapes.capb corners
run log: corners.runlog
#( Point { x: 0, y: 0 }, Point { x: 4, y: 3 } )
$ captain run shapes.capb nested
run log: nested.runlog
#( #( 1, 2 ), #( 3 ) )

captain run prints a list as a shape.

Shapes without a context

A shape whose items are unlabelled and whose first item is a literal of type i32, Text, bool or Symbol is a list of that type, wherever it appears: #( "a", "b" ) is a List[Text], and every item is held to it. That covers the common case of a literal list in a local:

Captain
module Example::Literal.

export firstPrime -> i32 [
  primes := #( 2, 3, 5, 7 ).
  ret primes at: 0.
].

Any other shape needs its type from the context: a ret from a procedure with a declared result, an argument to a typed parameter, a struct field, or a local that already has a type. Without one it is CAP-TYPE-012:

Refused by the checker: CAP-TYPE-012
module Example::Pairs.

export pair -> i32 [
  p := #( x: 1, y: 2 ).
  ret 1.
].

A labelled shape could be any struct with those fields, so the checker does not guess which. Write the type, Point { x: 1, y: 2 }, or put the shape where its type is known.

A shape that does not fit the type it is checked against is CAP-TYPE-013: a label on a list item, a missing or unknown field, or a shape where a number is expected.

Refused by the checker: CAP-TYPE-013
module Example::Points.

struct Point { x: i32, y: i32 }.

export origin -> Point [
  ret #( x: 0, z: 0 ).
].

Declarations such as cluster also take shapes of symbols in some of their clauses (regions: #( #Singapore )); the clause says what it accepts.

Lists as entry arguments

captain run cannot pass a list on the command line, so an export that takes one is not listed as a command-line entry point. A host embedding Captain can pass lists and records (Values in and out), checked against the declared element type exactly.