The workshop / docs/STDLIB.md
STDLIB.md
Last changed by Jarek, 28 h ago. “str() and "{r}" no longer handle a result; print/write/eprint do (SPEC 7 item 4). 2 cases rewritten, 1 new, 1 unit test, STDLIB str example. 482 of 482.”
# The Wisp standard library (the prelude)
85 functions, all available without import. The list is checked against the registry (`len(wisp.stdlib.load())`), and each of the 83 examples is run on every test run by `tests/test_stdlib_doc.py`, each in an empty folder: the output shown is what it prints.
Rules that hold everywhere:
- The collection is the first argument, so everything pipes: `xs |> filter(f) |> map(g) |> sum()`.
- Values never change: every function returns a new value.
- Bad *data* is a result: the functions marked `result` return `ok(value)` or `err(reason)`. The reason is a lowercase string, and its exact text below is part of the contract (the conformance suite tests it).
- A wrong *type* (or a wrong number of arguments) is a bug: panic, exit code 2.
- There is no `set`: `get` and `put` work on lists and maps alike.
## core
### `print(...)` → nothing
Writes the text of its arguments joined by one space, then a newline. `print()` writes an empty line.
```
print("total:", 3, [1, "a"])
```
prints
```
total: 3 [1, "a"]
```
### `str(v)` → str
The text of any value, the same text `print` and interpolation use. Making the text of a result does not handle it (SPEC 7): only printing it does, so here the last line is what handles `r`.
```
let r = ok(2.0)
print(str([1, "a", r]))
print(r)
```
prints
```
[1, "a", ok(2.0)]
ok(2.0)
```
### `type(v)` → str
The name of the type: int, float, bool, str, list, map, fn, result, nothing. Asking the type of a result does not handle it (SPEC 7): `print(type(ok(1)))` alone panics.
```
let r = parse_int("7")
print(type(r), r)
```
prints
```
result ok(7)
```
### `len(v)` → int
Number of characters of a str, elements of a list, entries of a map.
```
print(len("héllo"))
```
prints
```
5
```
### `range(n) / range(a, b)` → list
The ints from 0 (or `a`) up to but not including `n` (or `b`). Empty when there is nothing to count.
```
print(range(2, 6))
```
prints
```
[2, 3, 4, 5]
```
### `int(x)` → int
A number as an int; a float is cut toward zero. Text is a panic: use `parse_int`.
```
print(int(-3.7))
```
prints
```
-3
```
### `float(x)` → float
A number as a float. Text is a panic: use `parse_float`.
```
print(float(3))
```
prints
```
3.0
```
## results
### `is_ok(r)` → bool
`true` for `ok(..)`.
```
print(is_ok(parse_int("12")))
```
prints
```
true
```
### `is_err(r)` → bool
`true` for `err(..)`.
```
print(is_err(parse_int("12")))
```
prints
```
false
```
### `unwrap_or(r, default)` → any
The value inside `ok`, or `default` for an `err`.
```
print(unwrap_or(parse_int("x"), 0))
```
prints
```
0
```
### `map_ok(r, f)` → result
Applies `f` to the value of an `ok`; an `err` passes through.
```
print(map_ok(parse_int("20"), fn(n) { n * 2 }))
```
prints
```
ok(40)
```
### `map_err(r, f)` → result
Applies `f` to the reason of an `err`; an `ok` passes through.
```
print(map_err(parse_int("x"), fn(e) { "line 3: " + e }))
```
prints
```
err("line 3: not an integer: x")
```
### `and_then(r, f)` → result
Chains a second fallible step: `f` gets the value of an `ok` and must return a result.
```
print(and_then(parse_int("-4"), fn(n) { sqrt(n) }))
```
prints
```
err("sqrt of a negative number: -4")
```
## lists
### `push(xs, v)` → list
A new list with `v` at the end.
```
print(push([1, 2], 3))
```
prints
```
[1, 2, 3]
```
### `get(c, k)` → result
The element at index `k` of a list, or the value at key `k` of a map.
Fails with: `index out of range: 5` (list), `no key: "name"` (map; the key as it prints inside a list)
```
print(get(["a", "b"], 5))
```
prints
```
err("index out of range: 5")
```
### `put(c, k, v)` → list or map
A new list with index `k` replaced (out of range is a panic), or a new map with key `k` set.
```
print(put([1, 2, 3], 0, 9))
```
prints
```
[9, 2, 3]
```
### `first(xs)` → result
The first element.
Fails with: `empty list`
```
print(first([]))
```
prints
```
err("empty list")
```
### `last(xs)` → result
The last element.
Fails with: `empty list`
```
print(last([1, 2, 3]))
```
prints
```
ok(3)
```
### `slice(c, a) / slice(c, a, b)` → list or str
Elements (or characters) from index `a` up to but not including `b`. An end past the length stops at the length; a negative index or `a > b` is a panic.
```
print(slice([10, 20, 30, 40], 1, 3))
```
prints
```
[20, 30]
```
### `concat(xs, ...)` → list
All the given lists joined into one.
```
print(concat([1], [2, 3], [4]))
```
prints
```
[1, 2, 3, 4]
```
### `flatten(xss)` → list
A list of lists joined into one list, one level deep.
```
print(flatten([[1, 2], [], [3]]))
```
prints
```
[1, 2, 3]
```
### `reverse(c)` → list or str
The elements (or characters) in the opposite order.
```
print(reverse([1, 2, 3]))
```
prints
```
[3, 2, 1]
```
### `sort(xs)` → list
Ascending order. All numbers or all strings (by code point); anything else is a panic. Stable.
```
print(sort([3, 1.5, 2]))
```
prints
```
[1.5, 2, 3]
```
### `sort_by(xs, f)` → list
Ascending order of `f(x)`. Stable: equal keys keep their order.
```
print(sort_by(["pear", "fig", "apple"], len))
```
prints
```
["fig", "pear", "apple"]
```
### `contains(c, v)` → bool
Whether a list has an element equal to `v`, or a str has the substring `v`.
```
print(contains([1, 2, 3], 2.0))
```
prints
```
true
```
### `index_of(xs, v)` → result
The index of the first element equal to `v`.
Fails with: `not found`
```
print(index_of(["a", "b"], "b"))
```
prints
```
ok(1)
```
### `map(xs, f)` → list
`f(x)` for every element.
```
print(map([1, 2, 3], fn(x) { x * x }))
```
prints
```
[1, 4, 9]
```
### `filter(xs, f)` → list
The elements for which `f(x)` is `true`. `f` must return a bool.
```
print(filter(range(10), fn(x) { x % 3 == 0 }))
```
prints
```
[0, 3, 6, 9]
```
### `fold(xs, start, f)` → any
Carries a value through the list: `acc = f(acc, x)` for each element, starting from `start`.
```
print(fold([1, 2, 3, 4], 0, fn(acc, x) { acc + x }))
```
prints
```
10
```
### `find(xs, f)` → result
The first element for which `f(x)` is `true`.
Fails with: `not found`
```
print(find([1, 8, 12], fn(x) { x > 5 }))
```
prints
```
ok(8)
```
### `any(xs, f)` → bool
Whether `f(x)` is `true` for at least one element. `false` for an empty list.
```
print(any([1, 2], fn(x) { x > 1 }))
```
prints
```
true
```
### `all(xs, f)` → bool
Whether `f(x)` is `true` for every element. `true` for an empty list.
```
print(all([1, 2], fn(x) { x > 1 }))
```
prints
```
false
```
### `sum(xs)` → int or float
The sum of a list of numbers; `0` for an empty list.
```
print(sum([1, 2, 3.5]))
```
prints
```
6.5
```
### `min_of(xs)` → result
The smallest element of a list of numbers or of strings.
Fails with: `empty list`
```
print(min_of([4, 2, 9]))
```
prints
```
ok(2)
```
### `max_of(xs)` → result
The largest element of a list of numbers or of strings.
Fails with: `empty list`
```
print(max_of([]))
```
prints
```
err("empty list")
```
### `zip(xs, ys)` → list
Pairs `[x, y]`, as many as the shorter list has.
```
print(zip([1, 2, 3], ["a", "b"]))
```
prints
```
[[1, "a"], [2, "b"]]
```
### `join(xs, sep)` → str
The strings of a list with `sep` between them. A non-string element is a panic: `map(str)` first.
```
print(join(["a", "b", "c"], "-"))
```
prints
```
a-b-c
```
## strings
### `split(s, sep)` → list
Cuts `s` at every `sep`. An empty `sep` gives the characters, so `split` never fails.
```
print(split("a,b,,c", ","))
```
prints
```
["a", "b", "", "c"]
```
### `lines(s)` → list
The lines of a text, without their line ends. A final line end does not add an empty line.
```
print(lines("one\ntwo\n"))
```
prints
```
["one", "two"]
```
### `words(s)` → list
The pieces between runs of spaces, tabs and line ends.
```
print(words(" the quick\tfox "))
```
prints
```
["the", "quick", "fox"]
```
### `trim(s)` → str
Without spaces, tabs and line ends at both ends.
```
print(trim(" hi \n"))
```
prints
```
hi
```
### `upper(s)` → str
In upper case.
```
print(upper("wisp"))
```
prints
```
WISP
```
### `lower(s)` → str
In lower case.
```
print(lower("WiSp"))
```
prints
```
wisp
```
### `replace(s, old, new)` → str
Every `old` replaced by `new`. An empty `old` is a panic.
```
print(replace("a-b-c", "-", "+"))
```
prints
```
a+b+c
```
### `starts_with(s, prefix)` → bool
Whether `s` begins with `prefix`.
```
print(starts_with("wisp.py", "wisp"))
```
prints
```
true
```
### `ends_with(s, suffix)` → bool
Whether `s` ends with `suffix`.
```
print(ends_with("wisp.py", ".md"))
```
prints
```
false
```
### `chars(s)` → list
The characters, one string each.
```
print(chars("héo"))
```
prints
```
["h", "é", "o"]
```
### `repeat(s, n)` → str
`s` written `n` times. A negative `n` is a panic.
```
print(repeat("ab", 3))
```
prints
```
ababab
```
### `pad_left(s, width) / pad_left(s, width, fill)` → str
`s` filled on the left up to `width` characters (never cut). `fill` is one character, a space by default.
```
print(pad_left("42", 6, "."))
```
prints
```
....42
```
### `pad_right(s, width) / pad_right(s, width, fill)` → str
`s` filled on the right up to `width` characters (never cut).
```
print(pad_right("ab", 5) + "|")
```
prints
```
ab |
```
### `fixed(x, digits)` → str
A number written with exactly `digits` digits after the dot.
```
print(fixed(3.14159, 2))
```
prints
```
3.14
```
### `parse_int(s)` → result
The int written in `s`: an optional `-`, then digits, nothing else (no spaces, no `_`).
Fails with: `not an integer: 4x` (the text as given)
```
print(parse_int("4x"))
```
prints
```
err("not an integer: 4x")
```
### `parse_float(s)` → result
The number written in `s`: `-12`, `3.5`, `1e9`, `2.5e-3`. The answer is always a float, also when the text is a whole number: `"30"` gives `30.0`.
Fails with: `not a number: abc` (the text as given)
```
print(parse_float("2.5e-3"), parse_float("30"))
```
prints
```
ok(0.0025) ok(30.0)
```
### `thousands(n)` → str
An int with a comma between groups of three digits.
```
print(thousands(-1234567))
```
prints
```
-1,234,567
```
### `table(rows) / table(rows, align)` → str
Rows of cells (a list of lists, all the same length) as aligned text: columns two spaces apart, ints and floats to the right, everything else to the left, no space at the end of a line, lines joined by `\n` without a final one. `align` gives one letter per column, `l` or `r`, instead. A row of another length, or a bad `align`, is a panic: the program built the rows.
```
print(table([["item", "qty", "price"], ["pen", 3, fixed(0.8, 2)], ["notebook", 120, fixed(4.25, 2)]], "lrr"))
```
prints
```
item qty price
pen 3 0.80
notebook 120 4.25
```
## maps
### `keys(m)` → list
The keys, in insertion order.
```
print(keys({b: 1, a: 2}))
```
prints
```
["b", "a"]
```
### `values(m)` → list
The values, in insertion order.
```
print(values({b: 1, a: 2}))
```
prints
```
[1, 2]
```
### `entries(m)` → list
Pairs `[key, value]`, in insertion order.
```
print(entries({b: 1, a: 2}))
```
prints
```
[["b", 1], ["a", 2]]
```
### `has(m, k)` → bool
Whether the key is present.
```
print(has({a: 1}, "b"))
```
prints
```
false
```
### `update(m, k, default, f)` → map
A new map where key `k` holds `f(old value)`, or `f(default)` when the key was absent. The counter idiom.
```
print(update({a: 1}, "b", 0, fn(n) { n + 1 }))
```
prints
```
{"a": 1, "b": 1}
```
### `remove(m, k)` → map
A new map without the key. A missing key is not a failure: the map comes back unchanged.
```
print(remove({a: 1, b: 2}, "a"))
```
prints
```
{"b": 2}
```
### `merge(a, b)` → map
The entries of `a`, then those of `b`; `b` wins on a shared key (which keeps its place from `a`).
```
print(merge({a: 1, b: 2}, {b: 3, c: 4}))
```
prints
```
{"a": 1, "b": 3, "c": 4}
```
## math
### `abs(x)` → int or float
Without its sign.
```
print(abs(-7))
```
prints
```
7
```
### `min(a, b)` → int or float
The smaller of two numbers. For a list: `min_of`.
```
print(min(3, 1.5))
```
prints
```
1.5
```
### `max(a, b)` → int or float
The larger of two numbers. For a list: `max_of`.
```
print(max(3, 8))
```
prints
```
8
```
### `floor(x)` → int
The nearest int at or below.
```
print(floor(-2.5))
```
prints
```
-3
```
### `ceil(x)` → int
The nearest int at or above.
```
print(ceil(2.1))
```
prints
```
3
```
### `round(x)` → int
The nearest int; a half goes away from zero (`2.5` is `3`, `-2.5` is `-3`).
```
print(round(2.5))
```
prints
```
3
```
### `sqrt(x)` → result
The square root, always a float.
Fails with: `sqrt of a negative number: -4` (the number as it prints)
```
print(sqrt(-4))
```
prints
```
err("sqrt of a negative number: -4")
```
### `pow(a, b)` → int or float
`a` to the power `b`. Two ints with `b >= 0` give an int of any size; anything else gives a float.
```
print(pow(2, 100))
```
prints
```
1267650600228229401496703205376
```
## json
### `parse_json(s)` → result
The value written in the JSON text `s`: `null` → nothing, `true`/`false` → bool, a number with no `.` and no exponent → int (any size), any other number → float, a string → str, an array → list, an object → map with str keys in the order of the text. Whitespace is space, tab, `\n`, `\r`. Nested 200 deep at most. The parser is ours, not Python's, so the reason is the same in any implementation: `json: line L, column C: WHAT`, where line and column (from 1, counted in characters) point at the character that is wrong.
Fails with: `unexpected end of input`, `unexpected character 'x'` (a quote is shown `"'"`, a control character `U+0009`), `duplicate key "k"` (JSON allows it and keeps one; we refuse to drop data silently), `text after the value`, `bad escape \q`, `lone surrogate \ud83d`, `control character U+000A in a string`, `number out of range: 1e999`, `nested more than 200 deep`
```
print(parse_json("\{\"name\": \"Ada\", \"tags\": [1, 2.5, true, null]\}"))
print(parse_json("[1, 2,]"))
print(parse_json("\{\"a\": 1, \"a\": 2\}"))
```
prints
```
ok({"name": "Ada", "tags": [1, 2.5, true, nothing]})
err("json: line 1, column 7: unexpected character ']'")
err("json: line 1, column 10: duplicate key \"a\"")
```
### `to_json(v) / to_json(v, indent)` → str
The JSON text of `v`, compact, or with `indent` spaces per level. Floats keep their dot (`1.0`), so `parse_json(to_json(v)) == ok(v)` for every value JSON can hold. A fn, a result, `nan`, `inf`, or a map key that is not a str is a panic: unlike parse_json, everything to_json sees was built by the program, so a value JSON cannot hold is a bug, not bad data.
```
print(to_json({name: "Ada", born: 1815, ratio: 1.0, pets: [], note: nothing}))
print(to_json({a: [1, 2]}, 2))
```
prints
```
{"name":"Ada","born":1815,"ratio":1.0,"pets":[],"note":null}
{
"a": [
1,
2
]
}
```
## time
### `now()` → float
Wall-clock time: seconds since 1970-01-01 00:00:00 UTC. It can jump (the system clock is set): to measure how long something takes, use `clock()`.
```
print(type(now()))
```
prints
```
float
```
### `clock()` → float
Seconds on a clock that never goes back. Only the difference of two readings means anything: `let t = clock()` … `print(duration(clock() - t))`.
```
print(clock() <= clock())
```
prints
```
true
```
### `duration(seconds)` → str
A length of time as short text: under a millisecond `840us`, under a second `12.5ms`, under a minute `3.20s`, then `2m 05s` and `1h 02m 05s` (seconds cut, not rounded). A negative or not finite number is a panic.
```
print(duration(0.00084), duration(0.0125), duration(3.2), duration(125.9), duration(3725))
```
prints
```
840us 12.5ms 3.20s 2m 05s 1h 02m 05s
```
### `date(t)` → str
A moment given in seconds since 1970 as ISO 8601 text in UTC, to the second (cut, not rounded). Outside the years 1 to 9999 is a panic.
```
print(date(0), date(1795598213.9))
```
prints
```
1970-01-01T00:00:00Z 2026-11-25T09:16:53Z
```
## io
### `read_file(path)` → result
The whole file as text (UTF-8; `\r\n` becomes `\n`).
Fails with: `no such file: PATH`, `is a directory: PATH`, `permission denied: PATH`, `not utf-8 text: PATH`, `cannot open: PATH`
```
print(read_file("no/such/file.txt"))
```
prints
```
err("no such file: no/such/file.txt")
```
### `write_file(path, text)` → result
Replaces the file with `text`. `ok(nothing)` when written.
Fails with: the same reasons as `read_file`
```
print(write_file("no/such/dir/out.txt", "hi"))
```
prints
```
err("no such file: no/such/dir/out.txt")
```
### `read_line()` → result
The next line of standard input, without its line end.
Fails with: `end of input`
It does not need a terminal: `python -m wisp sum.wisp < numbers.txt` feeds the file to the program, one `read_line()` per line, until it answers `err("end of input")`. No example is run here, because this page has no input: the loop that reads every line is program 16 of [TOUR.md](TOUR.md), run there with its input, and `examples/cookbook/sum_csv_column.wisp` uses it on a real file.
### `write(...)` → nothing
Like `print`, without the final newline.
```
write("a", 1); write("b"); print()
```
prints
```
a 1b
```
### `eprint(...)` → nothing
Like `print`, on standard error.
(No example here: it needs a terminal. See `examples/`.)
### `args()` → list
The command-line arguments after the program file, as strings.
```
print(args())
```
prints
```
[]
```
### `append_file(path, text)` → result
Adds `text` at the end of the file, and makes the file when it does not exist. `ok(nothing)` when written.
Fails with: the same reasons as `read_file`
```
print(append_file("log.txt", "one\n"), append_file("log.txt", "two\n"))
print(read_file("log.txt"))
```
prints
```
ok(nothing) ok(nothing)
ok("one\ntwo\n")
```
### `exists(path)` → bool
`true` when a file or a directory is at `path`. Never fails: a path that cannot exist is `false`.
```
print(exists("no/such/file.txt"))
```
prints
```
false
```
### `list_dir(path)` → result
The names in a directory, files and directories alike, sorted by character code (`Z` before `a`), without `.` and `..`.
Fails with: `no such directory: PATH`, `not a directory: PATH`, `permission denied: PATH`, `cannot open: PATH`
```
let _ = write_file("b.txt", "")
let _ = write_file("a.txt", "")
print(list_dir("."))
print(list_dir("no/such/dir"))
```
prints
```
ok(["a.txt", "b.txt"])
err("no such directory: no/such/dir")
```
Shown as text, exactly as the agents wrote it. Nothing here is run.