appendix b

builtin reference

kanso keeps its standard library small enough to hold in your head, and it draws one line through it. a few names are ambient—if, print, push, put, delete, merge, length, entries, keys, and values resolve in any file with no import, because nearly every program touches them. everything else arrives through a std module: import "std/math" gives you math/sqrt, import "std/list" gives you list/map, and the qualified spelling in your source is the same spelling you will find in the entry headers below. the functions come in two shapes. most are ordinary pure functions—list/sort takes a list and returns a sorted one, math/sqrt takes a number and returns its root, with no trace left behind. the rest are descriptions: print, os/read_file, os/modified, io/write, os/write_file, os/args, io/stdin, io/read_line, time/sleep, and math/random don't perform i/o when evaluated—they return a value describing i/o that the runtime performs later (chapter 05). this appendix marks those description and treats the rest as plain functions.

every function here follows the same failure convention. an err or none the checker can see arriving is refused at the call, the way chapter 04 describes; one it cannot see passes straight through, unlooked-at, so a failure still rides out to whoever asks for it. a genuine type mismatch—list/sum on a list containing a string, math/sqrt on a record—is a program bug, not a value, and raises a runtime error at the point of the call. each entry below states both: what the function does, and what it does when the input is wrong. every example was run through the interpreter; every output block is copied from the machine, and the sources live under samples/appb/.

the sections that follow group the functions by what they operate on—numbers, text, lists, maps, bytes, choosing, and effects—and end each group with one program that exercises the lot. within a group the entries are alphabetical; the index above is the fast path when you know the name. the list section carries the largest surface, the verbs of std/list, and gives them a reference of their own.

numbers

the numeric helpers live in std/math; the two parsers live in std/text, beside the rest of the string-to-value work.

math/round

math/round number → int | none

rounds a float to the nearest integer, ties away from zero (2.5 becomes 3). NaN and the two infinities have no integer to round to, and ordinary arithmetic produces them, so for those three the answer is none and the caller's arm decides what it means. an int passes through unchanged and the checker types the call as int alone, so rounding a value you already know is whole owes no none arm. a non-number argument is a runtime error.

math/round!

math/round! number → int effect

the caller insisting the float is finite. the same rounding, answered in a box: .> opens it, and a NaN or an infinity is a failure inside it, round! takes a finite number, rather than a none. it is the choice xs[i] and xs[i]! make over a missing position, made over a float with no integer.

math/sqrt

math/sqrt number → float64

the square root, always a float—an int argument widens before the root is taken, so math/sqrt 9 is 3.0, not 3. a non-number argument is a runtime error.

text/to_float

text/to_float (string | int | float) → float64 | none

parses text into a float. an int widens and a float passes through, so the one function covers both parsing and numeric widening. text that is not a number answers none, and the caller's arm decides what that means.

text/to_float!

text/to_float! (string | int | float) → float64 effect

the caller insisting the text is a number. the same parse, answered in a box: .> opens it, and text that is not a number is a failure inside it whose reason quotes the text, "seven" is not a number.

text/to_int

text/to_int (string | int) → int | none

parses text into an integer; an int passes through unchanged. text that is not an integer answers none.

text/to_int!

text/to_int! (string | int) → int effect

the caller insisting the text is an integer. the same parse, answered in a box, with a failure inside it for text that is not one: "seven" is not an integer. the failure rides the railway past every step, so it reaches the endpoint rather than being silently swallowed.

numbers.kso
import "std/math"
import "std/text"

root = math/sqrt 2
print "sqrt {root}"
  .> (_ -> print "sqrt-int {math/sqrt 9}")
  .> (_ -> print "round {math/round 2.6}")
  .> (_ -> print "round-half {math/round 2.5}")
  .> (_ -> print "to_int {text/to_int "42"}")
  .> (_ -> print "to_float {text/to_float "3.14"}")
  .> (_ -> print "to_float-int {text/to_float 5}")
kanso run numbers.kso
sqrt 1.4142135623730951
sqrt-int 3.0
round 3
round-half 3
to_int 42
to_float 3.14
to_float-int 5.0

here is the failure on its own. ask to_int! for the number in a word and the failure inside its box goes past the .> step, so the print never happens and the failure surfaces at the endpoint, its birthplace named:

parse_fail.kso
import "std/text"

word = text/trim " seven "

text/to_int! word .> (n -> print "parsed {n}")
kanso run parse_fail.kso
error[endpoint]: unhandled err reached the entry: ""seven" is not an integer"
  born in the entry at parse_fail.kso:5

text and characters

text/char_code

text/char_code string → int

the unicode code point of a one-character string—char_code "A" is 65. the argument must be exactly one character; anything longer or shorter is a runtime error. its inverse is text/from_code.

text/chars

text/chars string → string[]

splits a string into its characters, each a one-character string, one per unicode scalar. accented letters count once—chars "café" has four elements, not five. a non-string argument is a runtime error.

text/ends_with?

text/ends_with? string string → bool

whether the first string ends with the second—ends_with? "kanso" "so" is true. every string ends with the empty string. its counterpart is text/starts_with?.

text/from_code

text/from_code int → string | err

the one-character string for a code point—from_code 233 is "é". an integer that is not a unicode scalar value returns an err, so surrogate halves and out-of-range numbers fail as values rather than producing garbage.

text/join

text/join string[] string → string

joins a list of strings with a separator between them—the counterpart to splitting. a failure inside the list propagates; a non-string element is a runtime error.

length

length (string | list | map) → int

a count: characters of a string, elements of a list, entries of a map. one function serves all three because "how many" means the same thing across them. anything else is a runtime error.

text/lowercase

text/lowercase string → string

the string with the letters A to Z made lower case. every other character, accented letters among them, comes back as it was: lowercase "HÉLLO" is "hÉllo". its counterpart is text/uppercase.

text/pad_end

text/pad_end string int string → string

the string with copies of the fill after it until it is the given number of characters long—pad_end "ab" 6 "-=" is "ab-=-=". the last copy is cut short where it would overrun. a string already that long comes back unchanged, and so does any string given an empty fill.

text/pad_start

text/pad_start string int string → string

the same as text/pad_end with the fill in front—pad_start "7" 3 "0" is "007".

text/replace

text/replace string string string → string | err

the first string with every occurrence of the second written as the third—replace "a,b,,c" "," ";" is "a;b;;c". occurrences are found left to right, and the search takes up again after the end of each one, so replace "aaaaa" "aa" "b" is "bba". a string that holds no occurrence comes back unchanged. an empty second string occurs everywhere, so it returns an err.

text/slice

text/slice (string | list) int int → string | list | none

text/slice text/span → string | list

a sub-range by 1-based inclusive positions—slice "kanso" 2 4 is "ans", and the same call shape works on lists. a range that runs past the end, or starts outside the value, answers none, as an index outside it does, so slice "kanso" 4 9 and slice "kanso" 0 2 are none rather than a shorter string. the empty range at either end, 1 0 or one past the last position, is inside. a range that ends exactly at the end is the tail, and an inverted range is the empty result. given a span alone, it answers the range the span holds, with no none, because a span is only ever made for a range inside its value.

strings.kso
import "std/text"

cs = text/chars "café"
print "chars {cs}"
  .> (_ -> print "length {length "café"}")
  .> (_ -> print "char_code {text/char_code "A"}")
  .> (_ -> print "from_code {text/from_code 233}")
  .> (_ -> print "join {text/join ["a" "b" "c"] "-"}")
  .> (_ -> print "slice {text/slice "kanso" 2 4}")
kanso run strings.kso
chars ["c" "a" "f" "é"]
length 4
char_code 65
from_code é
join a-b-c
slice ans

text/slice!

text/slice! (string | list) int int → (string | list) effect

the caller insisting the range is inside the value. the same slice, answered in a box: .> opens it, and a range that leaves the value is a failure inside it, slice! takes a range inside the value, rather than a none. an inverted range is still the empty result. it is the choice math/round! makes over a float with no integer. handed straight to text/utf8, text/append, text/to_int or text/to_float with .>, the range is read where it lies and no slice is built, when the value and both positions are names, integers or arithmetic on them.

text/starts_with?

text/starts_with? string string → bool

whether the first string begins with the second—starts_with? "kanso" "kan" is true. every string begins with the empty string, and a prefix longer than the string never matches.

text/uppercase

text/uppercase string → string

the string with the letters a to z made upper case, and nothing else changed: uppercase "café" is "CAFé". the name has no to_ because the answer is still a string; a to_ name, like to_int, answers a different kind of thing.

lists

two list operations are ambient—the subscript and push—because building a list and reading one position appear in nearly every program. everything else is the std/list vocabulary, covered as a group after the two.

xs[k]

(list | string | map)[index] → value | none

indexing. a list or string is indexed by a 1-based position; a map is indexed by its key. a missing position or absent key returns none—a dispatchable value, not an exception—so the caller decides what "not there" means. the strict form xs[i]! answers an effect, <t>effect, for the position that must be there: .> opens it, and a miss is the failure inside it. there is no bare function spelling; the subscript is the surface.

list/concat

list/concat list list → list

appends two lists into a new one, and neither input changes. the bytes text/bytes answers count as a list of their byte values, so list/concat (text/bytes "ab") [99] is [97 98 99]. strings do not go through it: two strings join by interpolation, "{a}{b}", and a list of them by text/join. a string the checker can see arriving is refused at the call.

push

push list value → list

a new list with one value appended. it is functional: the original list is unchanged, and the value's type is unconstrained. under the hood the runtime reuses the buffer in place when the list is uniquely owned, so the value semantics cost nothing when nobody else is looking.

the std/list vocabulary

import "std/list" — every verb takes its subject first

the vocabulary divides by what a verb returns. an adapter returns a lazy sequence: nothing is computed when you write list/map xs f, and each element flows through the whole chain one at a time when a consumer finally pulls. a consumer forces the sequence and returns an ordinary value. the split is why xs . list/map f . list/select p . list/sum allocates no intermediate list—and the compiler goes further, fusing the chain into a single flat scan, in this spelling or the nested one alike. every verb takes its subject first, which is what lets the pipe thread a collection through a chain without placeholders (chapter 05).

adapters — map coll f transforms each element. select coll pred keeps the elements the predicate approves; reject coll pred drops them—the two are deliberate complements, and there is no filter. take coll n stops after n elements and drop coll n skips the first n—both are what make the infinite generators usable. zip a b pairs two sequences element by element, ending with the shorter.

generators — infinite sequences, bounded by whatever consumes them. naturals counts 1, 2, 3, …; repeat value yields the same value forever; cycle coll loops a list end over end; iterate seed stretch yields seed, stretch seed, stretch (stretch seed), …. an unbounded consumer on an unbounded generator runs forever, which in kanso is a legal program, not an error—cap with take when you want an end.

consumers — fold coll init f is the root the others are built on: it threads an accumulator through every element. sum adds numbers (empty list is 0); mean averages as a float; count coll pred counts approvals; spread is the statistical spread, max minus min. all? coll pred and any? coll pred answer a question about the whole—the ? suffix marks every predicate in the language. find coll pred yields the first element the predicate approves, first and last take the ends, max and min the extremes, and argmax coll key / argmin coll key the element whose key is extreme. sort orders mutually comparable elements, and sort_by coll key orders them by what key answers for each, keeping elements whose keys tie in the order they arrived. reverse answers the elements last to first. to_sorted coll sorts the same way and answers a sorted, and find on a sorted halves the range instead of walking it, which needs a predicate that is false for a prefix of the order and true for the rest. to_list realizes an adapter chain into a plain list—the usual last step before printing. every empty-sequence extreme (max, min, find, first, last, argmax, argmin, spread) answers none, a value you dispatch on.

map builders — consumers whose result is a map. tally coll counts occurrences. group_by coll key files each element under its key, values in list buckets. index_by coll key keeps one element per key; to_h pairs builds a map from two-element pairs; transform_keys m f and transform_values m f rebuild a map through a function on each side of its entries. where two entries land on one key, the last write wins—the same rule put follows.

beneath the vocabulary sits one primitive: next, the pull protocol every adapter answers and every consumer drives. you only meet it when defining a sequence shape of your own; the other verbs are built from it.

lists.kso
import "std/list"
import "std/text"

xs = [3 1 2]
print "map {list/to_list (list/map xs (n -> n * 10))}"
  .> (_ -> print "select {list/to_list (list/select xs (n -> n > 1))}")
  .> (_ -> print "sort {list/sort xs}")
  .> (_ -> print "sum {list/sum xs}")
  .> (_ -> print "fold {list/fold xs 10 (acc n -> acc * n)}")
  .> (_ -> print "take {list/to_list (list/take list/naturals 4)}")
  .> (_ -> print "zip {list/to_list (list/zip xs ["a" "b" "c"])}")
  .> (_ -> print "tally {list/tally ["oat" "oat" "soy"]}")
  .> (_ -> print "group_by {list/group_by [1 2 3 4] (n -> n - n / 2 * 2)}")
  .> (_ -> print "spread {list/spread xs}")
  .> (_ -> print "push {push xs 4}")
  .> (_ -> print "at {xs[2]}")
  .> (_ -> print "length {length xs}")
  .> (_ -> print "slice {text/slice xs 1 2}")
  .> (_ -> print "concat {list/concat xs [9]}")
kanso run lists.kso
map [30 10 20]
select [3 2]
sort [1 2 3]
sum 6
fold 60
take [1 2 3 4]
zip [[3 "a"] [1 "b"] [2 "c"]]
tally { "oat":2 "soy":1 }
group_by { 0:[2 4] 1:[1 3] }
spread 2
push [3 1 2 4]
at 1
length 3
slice [3 1]
concat [3 1 2 9]

note xs[2] is 1—position two of [3 1 2], one-based. when the position is absent, the subscript hands back none, and because none is a value you dispatch on it. two overloads of describe—one that matches none, one that matches anything—turn "missing" into an ordinary branch:

missing.kso
fn describe none
  "index out of range"

fn describe x
  "value is {x}"

found = describe [10 20 30][2]
gone = describe [10 20 30][9]
print "in-range: {found}" .> (_ -> print "missing: {gone}")
kanso play missing.kso
in-range: value is 20
missing: index out of range

the direct call describe xs[9] is deliberate. the pipe . short-circuits a failure before it reaches the function, so xs[9] . describe would propagate the none untouched; to dispatch on none you hand it to the function as an argument, where the none overload can match it.

maps

entries

entries map → entry[]

the key–value pairs of a map, each an entry key value record, returned in sorted key order. the order is deterministic, always—iteration over a map never depends on insertion history. an entry reads its two fields by name, e.key and e.value, and a parameter can take it apart with the pattern (entry k v) instead. to read a single value by key, use the subscript m[k].

keys

keys map → key[]

the keys of a map as a list, in the order entries gives them.

values

values map → value[]

the values of a map as a list, in the same order. position i of keys m, of values m and of entries m all describe the same pair, so a walk that wants both sides can index the two lists and never build a record.

delete

delete map key → map

a new map without key. a key that is not there answers a map equal to the one given, and the map you handed in is never changed. like put it needs no import, and the keys it accepts are the ones put accepts: ints and strings.

put

put map key value → map
put list position value → list | none

a new map with key set to value, replacing any previous binding. keys are ints or strings. like push it is functional and made in-place by the runtime when the map is uniquely owned. building a map from nothing starts at the empty-map literal {}; a literal with known keys is written { "a":1 "b":2 }.

maps.kso
blank = {}

base = { "a":1 "b":2 }
grown = put base "c" 3
print "literal {base}"
  .> (_ -> print "put {grown}")
  .> (_ -> print "at {grown["b"]}")
  .> (_ -> print "entries {entries grown}")
  .> (_ -> print "keys {keys grown}")
  .> (_ -> print "values {values grown}")
  .> (_ -> print "length {length grown}")
  .> (_ -> print "empty {blank}")
kanso run maps.kso
literal { "a":1 "b":2 }
put { "a":1 "b":2 "c":3 }
at 2
entries [entry "a" 1 entry "b" 2 entry "c" 3]
keys ["a" "b" "c"]
values [1 2 3]
length 3
empty {}

on a list, put answers a new list with the element at position replaced. positions count from 1, as xs[i] reads them, and a position outside the list answers none, as a read there does. a position that is not an int stops the run. the list you handed in is never changed, and a list nothing else holds is written where it stands, so a loop that rewrites a vector copies nothing.

positions.kso
cells = [0 0 0 0]
marked = put cells 2 7
print "put {marked}"
print "kept {cells}"
print "outside {put cells 5 1}"
kanso run positions.kso
put [0 7 0 0]
kept [0 0 0 0]
outside <none>

records

merge

merge record { "field":value … } → record

a copy of record with the named fields replaced and every other field carried over. the fields are named by string literals in a map literal, and each has to be a field of the record's type: a name the type does not declare is refused when the compiler can see the type, and otherwise when no record the module declares has every field named. a value that reaches the merge at run time with a type that lacks one of the fields is a runtime error. only the module that declares the type may merge it, the same rule as construction.

shipping.kso
type order
  item
  qty
  status

placed = order "tea" 2 "placed"
shipped = merge placed { "qty":3 "status":"shipped" }
print "{shipped}" .> (_ -> print "{placed}")
kanso play shipping.kso
shipping/order "tea" 3 "shipped"
shipping/order "tea" 2 "placed"

bytes and encoding

text/bytes

text/bytes string → int[]

the utf-8 encoding of a string as a list of byte values (0–255). an ascii string gives one byte per character; "café" gives five bytes, because é takes two. this is the entry point to byte-level work—scanning, chunking, decoding—used heavily by the json library in chapter 13.

text/find2

text/find2 int[] int int int → int

scans a byte list from a 1-based start index for the first byte equal to either of two targets—hence the 2—and returns its 1-based position. when neither target is found it returns length + 1, one past the end, a sentinel you can compare against without a branch. it is the hot primitive behind tokenizers that stop at "the next comma or brace".

text/span

type text/span — whole, from, to

a range of positions inside one string or byte list. whole is the value, and from and to are 1-based and inclusive, counted the way text/slice counts; an empty range has to one less than from. the fields read like any record's, as run.from. only std/text builds a span, and only after checking that the range lies inside whole, so text/slice on a span cannot miss and answers no none.

text/span_to

text/span_to int[] int int int → text/span | none

the span from a 1-based start up to the byte before the first byte equal to either of two targets, or to the end of the bytes when neither comes. it is text/find2 answering the range it scanned instead of the position where it stopped. a start one past the end answers the empty span there; a start anywhere else outside the bytes answers none.

text/span_to_below

text/span_to_below int[] int int int int → text/span | none

text/span_to with one more place to stop: any byte below the limit in the last argument. a json string ends at a quote or a backslash, and a control character below 32 inside one is an error, so a decoder scans with all three.

spans.kso
import "std/text"

fn shown none
  "none"

fn shown run
  "{run.from}..{run.to} {text/utf8 (text/slice run)}"

bs = text/bytes "key=value;next"
tab = text/bytes "ab\tc"
print "key {shown (text/span_to bs 1 61 59)}"
  .> (_ -> print "value {shown (text/span_to bs 5 61 59)}")
  .> (_ -> print "end {shown (text/span_to bs 15 61 59)}")
  .> (_ -> print "outside {shown (text/span_to bs 0 61 59)}")
  .> (_ -> print "below {shown (text/span_to_below tab 1 44 59 32)}")
kanso play spans.kso
key 1..3 key
value 5..9 value
end 15..14 
outside none
below 1..2 ab

the first span runs from position 1 to the byte before the = (61). the third starts one past the fourteen bytes, so it is empty, and the fourth starts outside them and is none. the last stops at the tab, byte 9, which is below the limit of 32.

text/to_span

text/to_span (string | int[]) int int → text/span | none

the span of a value from one position to another, counted the way text/slice counts, when that range lies inside the value, and none when it does not. to_span bs 2 4 covers the second through fourth bytes. an empty range, with to one less than from, may sit anywhere from the start to one past the end, and anything wider or further out is none. it is the bounds check the other functions here make, written out for a range you already hold.

text/utf8

text/utf8 int[] → string | err

the inverse of text/bytes: decodes a list of byte values back into a string. a value outside 0–255, or a byte sequence that isn't valid utf-8, is a failure. a caller outside the standard library that wants to ask whether bytes were utf-8 rescues it with .?, which is licensed because the failure is std/text's.

bytes.kso
import "std/text"

bs = text/bytes "café"
print "bytes {bs}"
  .> (_ -> print "utf8 {text/utf8 bs}")
  .> (_ -> print "find2 {text/find2 (text/bytes "a,b;c") 1 44 59}")
kanso run bytes.kso
bytes [99 97 102 195 169]
utf8 café
find2 2

the find2 call searches the bytes of "a,b;c" from position 1 for a comma (44) or a semicolon (59). the comma sits at position 2, so that is the answer; had neither appeared, the result would have been 6—one past the five bytes.

choosing

if

if bool a b → value

chooses between two values by a boolean condition, and it is the only builtin that does not evaluate all its arguments: the untaken branch never runs, so if is safe to guard an expensive or failing computation. the condition must be true or false; anything else is a runtime error. in most code the dispatch of chapter 03 replaces if entirely—if is for the small, local two-way choice that isn't worth a second overload.

control.kso
fn classify n
  if (n > 0) "positive" "non-positive"

print "seven {classify 7}" .> (_ -> print "zero {classify 0}")
kanso play control.kso
seven positive
zero non-positive

effects

the functions marked description in this group return io values, which describe work to be done. evaluating them performs no i/o; they build a value the runtime executes afterward, which is why the same program can be run, planned with --plan, or fed to a scripted executor in a test (chapter 05). .> pipes the value a description will yield into a function; when that function ignores the value, as _ -> next does, the two descriptions run one after the other.

os/args description

os/args → io (yields string[])

yields the command-line arguments—everything after -- on the invocation—as a list of strings. the list exists only at execution time, so an index past its end is answered the way every absent index is: with none, a value the caller dispatches on. reach for xs[i]! when the position must be there and its absence should end the run.

argv.kso
import "std/os"

fn first xs
  xs[1]

os/args .> first .> print
kanso play argv.kso -- clay
clay
kanso play argv.kso
<none>

wrap_err

wrap_err reason err → failure

a new failure carrying your reason, with the err it wraps kept as its cause. it takes an err out of its box, the one a rescue hands its callback, so it is written inside a .? step. the endpoint report prints the chain, each link keeping its own birthplace, so re-raising under a name of your own never loses where the trouble started. the err it wraps is std/text's here, which is the usual shape: a rescue opens only a failure another package raised, and wrapping is what you do to a failure that reached you from elsewhere, so the report can say what you were doing when it arrived:

wrap_err.kso
import "std/text"

type config_bad
  file

fn low_read _
  text/utf8 [255]

fn relabel e:err
  wrap_err (config_bad "app.conf") e

low_read 0 .? relabel
kanso play wrap_err.kso
error[endpoint]: unhandled err reached the entry: wrap_err/config_bad "app.conf"
  born in relabel at wrap_err.kso:10
  caused by: "invalid utf-8"
  born in text/utf8 at std/text/text.kso:122

effect description

effect value → io (yields value)

a description that yields the value it was handed. it builds the box by hand, so a chain can start from a plain value and a function that sometimes has work to describe and sometimes has an answer ready can return a description either way. an err a rescue took out of its box goes back in, so effect e inside a callback is the failure again. a failure handed to it is content: with broken holding a failure std/text raised, effect broken is a description that yields the err, which the .? step sees and the .> step skips, the same as a failure a read raised. the rescue licence is foreign-only, so a box built over this file's own err hands it on to the endpoint instead. the value stays boxed until a chain word opens it, so effect 5 + 1 is refused at compile time.

effect.kso
import "std/text"

broken = text/split "a" ""

effect 5 .> (n -> print "got {n}")
  .> (_ -> effect broken .? (e -> "rescued {e.reason}") .> print)
kanso run effect.kso
got 5
rescued split needs a separator; text/chars answers the characters

print description

print string → io

a description of writing one line to standard output. it takes a string, and only a string—to print a number or a list, interpolate it into one with "{value}". handing print a bare non-string is a runtime error with exactly that advice. sequence prints with .> (_ -> ...); render the sequence without running it with --plan.

print.kso
print "first" .> (_ -> print "second") .> (_ -> print "third")
kanso run print.kso
first
second
third
kanso run print.kso --plan
plan:
  print "first"    # from line 1
  print "second"    # from line 1
  print "third"    # from line 1

math/random description

math/random int → io (yields int)

a description that yields an integer in the half-open range [0, bound). a bare run seeds the generator from the clock, so each run draws different numbers. set KANSO_SEED to an integer and every draw replays exactly, on either engine; the flow chapter shows it. pipe the yielded value into a function with .>.

time/sleep description

time/sleep int → io

a description of pausing for a number of milliseconds. the pause is real: time/sleep 1500 takes a second and a half on the clock, on either engine. other fibers run while one sleeps. sequence it with .> (_ -> ...).

timing.kso
import "std/math"
import "std/time"

pub play = time/sleep 10 .> (_ -> math/random 6) .> show

fn show n
  print "rolled {n}"
kanso run timing.kso
rolled 2
kanso run timing.kso --plan
plan:
  sleep 10
  random 6
  . <continuation>

the plan names sleep and random up front, then stops at . <continuation>—honest notation for "what show does depends on a value the roll hasn't produced yet." a step written _ -> next ignores the value it is handed, so the plan can list it; show reads its value, so the plan stops there. the plan renders that step with a bare dot, which is the notation of the printed plan rather than the operator you write.

std/pool description

pool/make int → io (yields pool)
pool/take pool → io (yields a value)
pool/give pool value → io
pool/with pool (value → io) → io

a pool holds up to a fixed number of values that fibers share, such as open database connections. pool/make n yields an empty pool that holds up to n values. pool/give puts a value in, and waits while the pool is full. pool/take takes one out, and waits while the pool is empty. a take promises no particular value, but every engine answers the same one, so a run replays. pool/with p work takes a value, hands it to work and gives it back when the work ends, whether the work succeeded or failed, so a failure part way through cannot lose the value. the failure still rises with its reason and the place it was born.

pooled.kso
import "std/pool"
import "std/time"

fn filled p
  pool/give p "cup" .> (_ -> pool/give p "mug") .> (_ -> four p)

fn four p
  served p "ana"
  served p "ben"
  served p "cy"
  served p "dee"

fn served p name
  pool/with p (c -> drink name c)

fn drink name c
  print "{name} has the {c}"
    .> (_ -> time/sleep 5)
    .> (_ -> print "{name} is done")

pool/make 2 .> filled
kanso play pooled.kso
ana has the mug
ben has the cup
ana is done
ben is done
cy has the cup
dee has the mug
cy is done
dee is done

four fibers share two values. ana and ben take them at once; cy and dee wait until those two give them back. a waiting fiber costs nothing while it waits. when every fiber is waiting on a pool, none of them can ever be woken, so each waiting take or give answers an err saying so, and the program ends with those reasons instead of hanging.

os/modified description

os/modified string → io (yields int | file_not_found)

a description that yields when a file last changed, in milliseconds since the epoch, the unit time/now answers in. a path that is not there yields file_not_found, as it does for os/read_file. comparing two readings is how a program notices that a file changed under it.

os/random_bytes description

os/random_bytes int → io (yields bytes)

a description that yields that many bytes from the operating system's secure source: getrandom or arc4random_buf on a machine, and crypto.getRandomValues in the browser. use it for salts, keys and tokens, where math/random is wrong because KANSO_SEED replays it. that seed has no effect here, so a seeded run is still reproducible in every respect except the bytes a secret is made of. a count that is not a non-negative integer is a runtime error.

os/read_file description

os/read_file string → io (yields string | file_not_found)

a description that yields the contents of a file. a path that is not there yields file_not_found, which carries the path and dispatches like any other value — an absent file is an outcome a program can anticipate, so it is data. anything else that stops the read — a permission, a device, bytes that are not text — fails at execution time, at the executor, when the read is actually attempted rather than when the description is built. pipe the contents into a function with .>.

os/read_file! description

os/read_file! string → io (yields string)

the caller insisting the file is there. same read, and a path that is not there bubbles as a failure instead of arriving as data — the choice foo[k] and foo[k]! make over a missing key, made over a missing file.

io/write description

io/write string → io

a description of writing a string to standard output exactly as given—no newline. print is the whole-line form; write is for assembling a line from pieces, and for streaming: a chain that writes a chunk and binds the rest (io/write chunk .> (_ -> more)) builds each chunk only when the executor reaches it, so output of any size flows in constant memory.

write_stream.kso
import "std/io"

io/write "no newline "
  .> (_ -> io/write "between these")
  .> (_ -> print "; print ends the line")
kanso run write_stream.kso
no newline between these; print ends the line

os/write_file description

os/write_file string string → io

a description of writing a string to a path, replacing any existing contents. it yields done, so the next step is normally bound with .> (_ -> ...), which ignores it. here one program writes a file and then reads it straight back:

files.kso
import "std/os"

os/write_file "note.txt" "one taiyaki"
  .> (_ -> os/read_file! "note.txt")
  .> print
kanso run files.kso
one taiyaki

io/read_line description

io/read_line → io (yields string | done)

a description that yields the next line of standard input without its ending, which may be \n or \r\n. once the input has ended it yields done. each read happens at its place in the chain, and anything written before it has reached the terminal before the read waits, so a loop that prints a prompt and then reads behaves the way it reads. io/stdin takes whatever input is left in one piece.

io/stdin description

io/stdin → io (yields string)

a description that yields all of standard input as a single string. pipe it into a function to process what was fed on the pipe:

input.kso
import "std/io"

io/stdin .> shout .> print

fn shout text
  "{text}!!"
kanso play input.kso < pipe.txt
hello from a pipe!!
err - always arrives, never uninvited
err

hand me to a builtin and i pass straight through—list/sort, list/map, list/sum, none of them inspect me; they return me. a type mistake is different: list/sum on a list with a string in it is a bug in your program, and that raises where it happens.

that is the whole surface: the ambient names, a handful of std modules, two shapes, one failure convention. (std/json, the decoder the book builds by hand in chapter 13, ships ready-made too.) you now have the signature, the behavior, and the failure mode of everything kanso offers—enough to read any program in this book without guessing what a call does, and enough to reach for the right verb instead of hand-rolling it. the chapters build real programs on exactly this surface; the json library of chapter 13 is little more than text/bytes, text/find2, and text/slice worn smooth.

exercises

  1. write a program that reads a file of numbers, one per line, and prints their sum. you will need os/read_file, text/chars or a split, text/to_int, and list/sum—decide how a non-numeric line should behave, and make that behavior visible in the output.
  2. using only text/bytes, text/find2, and text/slice, split a string on its first comma into a "before" and an "after". confirm with --plan that no i/o happens until you print the two halves.
  3. the lenient subscript xs[i] answers a missing index with none while the strict form xs[i]! answers a box whose failure is the miss. write one small program that shows both on the same out-of-range access, and explain in a comment which you would choose for a lookup that is expected to miss.
  4. write a two-overload label function—one arm matching none, one matching a value—and drive it from a math/random roll that indexes into a short list. run it a few times and note that the roll is the same each run.