(std prelude)

Reference

Overview

What every module has access to without importing anything: collections, strings, files, ports, concurrency and the macros the language is written with.

(defun (main)
  (def words (string-split (file-read-text "notes.txt") " "))
  (println #"${(length words)} words")
  0)

Every module outside the standard library imports (std prelude) without saying so, unless it imports it itself, with modifiers, to hide or rename part of it. Its forms come from three places: the definitions in std/prelude.bjo and the files it includes, the names it re-exports from (std eq) and (std maths), whose docs are in those modules, and the builtins compiled into the runtime, whose docs are here.

Collections. List is the immutable linked list, Vec the persistent vector (an rrb tree), Map the persistent hash map (a champ), and .NET arrays are there for interop and speed. Each has functions of its own, named after it (list-map, vec-ref, map-set), and a builder or a transient for building one in a loop.

Iteration. The traits Iterable, Collection, Cursor and Collector are what loop and the generic fold, map, filter and length work through, so those work on every collection, on strings, on ranges and on lazy Seqs.

Strings and characters. A string is UTF-8, and positions in one are cursors rather than indices. A char is a Unicode scalar value.

Files and ports. Files are read and written whole, or through ports. The file system is reached through the FS effect, so it can be mocked, and logging through the warn and log effects.

Concurrency. Bjoroutines run on fibers, which meet on channels through Concurrent ML events (sync, choose, wrap), inside scopes that wait for them, cancel them, and raise their failures (with-scope, with-deadline).

Macros. cond, if-let, some->, get, type/derive and the reader extensions #map and #ch are macros, and the syntax functions macro transformers use are here as well.

See also: println, displayed, fold, map, list-map, vec-map, map-ref, str, file-read-text, read-line, sync, with-scope, cond

Reference

Types

Functions

Values

Macros

Types

Written

trait ↑ Types

Trait for the text a value is written as, which the reader reads back.

As Scheme’s write: a string is in quotes with its escapes, a char is #\a, a long is 21L, and a double always has a point, such as 2.0. A float, an int128 and a uint128 have no suffix, and are written with their type: (: 2.5 float). An implementation gives write-into; written by default rents a builder and calls it. A type whose text is at hand gives written too, and adds it in write-into.

Every type is Written. With no implementation of its own, a type is written as .NET’s ToString gives it, in the invariant culture.

See also: written, write-into, Displayed

Displayed

trait ↑ Types

Trait for the text a value shows a person.

As Scheme’s display: a string is its text, without quotes. Every Displayed type is Written. A type with no implementation of its own is displayed as it is written. println, print and #"...${x}..." use displayed.

The containers display their elements displayed and write them written: a List as (1 2 3), a Vec as [1 2 3], an Array as #[1 2 3], a Map as #map((k v) ...), an Option as (Some x) or None, a Result as (Ok x) or (Err e), a Tuple as (Tuple 1 2), and a Box as (Box x). A Seq is (Seq ...), without being walked.

See also: displayed, display-into, Written

Box

record ↑ Types

A mutable cell holding one value.

%a
What it holds.
(def count (make-box 0))
(box-set! count (+ (box-ref count) 1))
(deref count)   ; 1

A one-element array behind an opaque struct. Copying a box copies the reference to the array, so every copy reads and writes the same cell. It has a Derefable implementation, so deref and get read it, and prints as (Box x).

See also: make-box, box-ref, box-set!, deref

Exception

type alias ↑ Types

System.Exception, the type every .NET exception derives from.

The error type of the prelude’s fallible operations, such as (Result Exception InputPort). The Err carries the real .NET exception, so a handler can test for a more specific type.

See also: raise, Err

Iterable

trait ↑ Types

Trait for sequentially iterable collections, used by (:for x s) loops.

%s
The iterable collection or sequence type.
(loop (:for x '(1 2 3))
      (:acc (summing x)))          ; 6

(->list (map (fun (x) (* x x)) (range 0 4)))   ; (0 1 4 9)

An implementation defines two associated types: %elem (the element yielded) and %cursor (the cursor type), and implements the four core methods: iterable-start, iterable-done?, iterable-current, and iterable-next.

Default implementations are provided for iterable-end, iterable-cleanup, fold, map, filter, take, drop, take-while, drop-while, seq-enumerate, flat-map, any?, all?, find, for-each, and ->seq. Methods returning a Seq are lazy; fold, any?, all?, find, and for-each execute eagerly.

iterable-end may be called after iterable-done? answered true, or a second time, and must then do nothing.

enumerate and zip are not methods: they make adapters, structs around iterables that are iterables themselves, with no Seq in between.

See also: iterable-start, iterable-done?, iterable-current, iterable-next, iterable-end, iterable-cleanup, fold, map, ->seq

Enumerated

record ↑ Types

What enumerate gives: an iterable around %s whose elements are paired with their index.

%s
The iterable it walks.
inner
The iterable.

See also: enumerate

Zipped

record ↑ Types

What zip gives: an iterable of the elements of %l and %r in pairs.

%l
The left iterable.
%r
The right iterable.
left
The left iterable.
right
The right iterable.

See also: zip

Cycled

record ↑ Types

What in-cycle gives: an iterable of the elements of %s, over and over.

%s
The iterable it walks again and again.
inner
The iterable.

See also: in-cycle

Pairwise

record ↑ Types

What pairwise gives: an iterable of each element of %s with the one after it.

%s
The iterable it walks.
inner
The iterable.

See also: pairwise

Chained

record ↑ Types

What chain gives: an iterable of the elements of %a and then of %b.

%a
The first iterable.
%b
The second iterable, of the same element type.
first
The first iterable.
second
The second iterable.

See also: chain

Repeated

record ↑ Types

What in-repeat gives: an iterable of one value, a number of times or without end.

%a
The value's type.
item
The value.
times
How many times; int-min for without end.

See also: in-repeat

Cursor

trait ↑ Types

Bidirectional cursor trait for collections navigable forward and backward.

%s
The collection type.

An implementation defines %elem and %cursor and provides the six core cursor methods. Every method takes the collection as well as the cursor.

The prelude implements it for string, with StringCursor as the cursor type.

See also: cursor-start, cursor-end, cursor-ref, cursor-next, cursor-prev, string-cursor-start

Summing

union ↑ Types

The collector that adds up numbers.

%a
The type of the numbers, and of the sum.
summing
The collector: (summing x) adds x each step.
{summing x (:for x (range 1 5))}   ; 10
{summing x (:for x [0.5 0.25])}    ; 0.75

Starts from 0, and its result is the total. It works at every numeric type, through (where (Num %a)) on its implementation: the sum has the type of the values it adds, and a sum of anything else is a type error at the loop.

See also: Counting, Folding, collector-step

Counting

union ↑ Types

The collector that counts its steps.

%a
The type of the stepped value, which is ignored.
%n
The type of the count.
counting
The collector: (counting x) adds one each step, whatever x is.
(loop (:for x xs)
      (:acc n (counting x) #:when (even? x))
      => n)                     ; how many are even
{counting x :when (even? x) (:for x xs)}   ; the same

Starts from 0. The step expression is evaluated and its value dropped. The count is a number of the type its use asks for, a long say, and an int when nothing asks, as a literal is.

See also: Summing, Folding

Folding

union ↑ Types

The collector that keeps the last value stepped into it.

%a
The type of the value kept.
folding
The collector, with the value to start from: (folding init expr).
(loop (:for x xs)
      (:acc total (folding 0 (+ x total)))
      => total)                 ; a fold, written as a loop

(:acc name (folding init expr)) starts name at init and replaces it with expr’s value at every step. Since expr may read name, that is a fold, and it is how fold, any?, all? and find are written. :final uses one too.

See also: fold, Summing, Counting

Range

record ↑ Types

An integer range from lo up to but not including hi, in steps of one.

lo
The first integer, included.
hi
The upper bound, not included.

Implements Iterable and Collection. Traversal stops at the first value at or above hi, counting upward only. Use down-from to count downward.

A range from below zero to above it can hold more values than an int counts. Its walk is correct, and length panics.

See also: range, RangeBy, up-from

RangeBy

record ↑ Types

An integer range from lo up to but not including hi, in steps of by.

lo
The first integer, included.
hi
The upper bound, not included.
by
The positive step.

Implements Iterable and Collection. The step after the last value can pass int-max, so the walk counts in a long, where it cannot wrap round below hi, and ends at the first value at or above hi. It costs one comparison per step, as a Range’s walk does.

As for a Range, length panics when the range holds more values than an int counts.

See also: range-by, Range, up-from

UpFrom

record ↑ Types

An iterable sequence of ints counting upward; returned by up-from.

from
The first int.
to
The bound, not included.
by
The step, positive.

See also: up-from, DownFrom

DownFrom

record ↑ Types

An iterable sequence of ints counting downward; returned by down-from.

from
The first int.
to
The bound, included.
by
The distance subtracted each step, positive.

See also: down-from, UpFrom

ListTails

record ↑ Types

The sequence of list tails returned by over-list.

%a
The type of the list's elements.
rest
The list the walk starts from.

Its Iterable implementation yields the list, then its tail, and so on, stopping before Nil. Each element is a (List %a) with a head.

See also: over-list

Listing

union ↑ Types

The collector that gathers a loop’s values into a list.

%a
The type of the elements.
listing
Written (listing x) in an :acc clause, or as the head of a comprehension.
(loop (:for x (list 1 2 3))
      (:acc out (listing (* x 10)))
      => out)                        ; (10 20 30)

{listing x :when (> x 2) (:for x (range 0 6))}   ; (3 4 5)

The list is in the order the values were added. It is built with a list builder, so each value costs O(1) and nothing is reversed at the end.

See also: listbuilder-empty, ListingReverse

ListingReverse

union ↑ Types

The collector that gathers a loop’s values into a list, the last value first.

%a
The type of the elements.
listing/reverse
Written (listing/reverse x) in an :acc clause, or as the head of a comprehension.
(loop (:for x (list 1 2 3))
      (:acc out (listing/reverse (* x 10))))   ; (30 20 10)

{listing/reverse x (:for x (range 0 4))}       ; (3 2 1 0)

Each value is consed onto the list so far: the list is the values in the reverse of the order they were added, as a loop that conses onto an accumulator makes it. A value costs one cons, and the loop ends with the list as it is, where listing adds to a builder and makes the list from it at the end.

See also: Listing

TransientVec

type alias ↑ Types

A vec that is changed in place at either end and at any index, and turned back into a vec in O(1).

%a
The element type.
(def t (vec->transientvec [1 2 3]))
(transientvec-add-first! t 0)
(transientvec-add! t 4)
(transientvec-pop-first! t)    ; 0
(transientvec-set! t 0 10)
(transientvec->vec t)          ; [10 2 3 4]

A transient is for many changes in a row to one vec, where each persistent vec-add or vec-pop-first would copy a part of the vec. It holds the vec’s head and tail, a leaf’s worth at each end, in arrays of its own, and adds and removes there in place. Once in a leaf’s worth of operations at an end, that end runs out or fills, and the transient moves a leaf between it and the tree, as a vec does.

Sharing. vec->transientvec shares the vec’s tree, and copies a part of it the first time it changes it, so the vec is not changed. transientvec->vec hands what the transient holds to a vec in O(1), and the transient copies what it handed over before it changes it again. The transient stays usable.

Against a builder. A transient is the same structure as a vec builder. A builder is for making a vec by adding at its end; a transient for changing one at both ends.

A transient is not safe to use from two threads at once.

Traits. Implements Collection and Addable!, which adds at the end.

See also: vec->transientvec, transientvec->vec, transientvec-add!, transientvec-pop!, transientvec-add-first!, transientvec-pop-first!, vecbuilder-empty

Vecing

union ↑ Types

The collector that gathers a loop’s values into a vec.

%a
The element type.
vecing
The collector itself, written (vecing x) in an :acc clause.
(loop (:for x '(1 2 3))
      (:acc v (vecing (* x x))))   ; [1 4 9]

Its accumulator is a VecBuilder: each value is added in place, and the builder is frozen into a vec when the loop ends.

See also: Collector, vecbuilder-empty

VecingSmall

union ↑ Types

The collector that gathers a loop’s values into a vec that is likely small.

%a
The element type.
vecing/small
The collector itself, written (vecing/small x) in an :acc clause.
(loop (:for x '(1 2 3))
      (:acc v (vecing/small (* x x))))   ; [1 4 9]

Gives the same vec as vecing. Its builder is one from vecbuilder-empty/small, which makes a vec of a few elements with less allocation and copying. For a vec of many elements it is a little slower than vecing.

See also: Vecing, vecbuilder-empty/small

VecBackCursor

type alias ↑ Types

A cursor walking part of a vec backwards.

%a
The element type.

A value that walks the vec’s leaf arrays from the end, as vec-cursor walks them from the start: nothing is allocated for a walk.

See also: vec-back-cursor, ReverseVecSlice, vec-cursor

VecSlice

record ↑ Types

A run of a vec, which a loop walks front to back.

%a
The element type.
items
The vec.
from
The first index walked.
count
How many elements are walked.

Made by in-vec, which checks the bounds. A value, and so is its cursor, so a loop over one allocates nothing.

See also: in-vec, vec-cursor-slice

ReverseVecSlice

record ↑ Types

A run of a vec, which a loop walks back to front.

%a
The element type.
items
The vec.
last
The first index walked, the highest of the run; -1 for an empty run.
count
How many elements are walked.

Made by in-reverse-vec, which checks the bounds.

See also: in-reverse-vec, VecBackCursor

ArraySlice

record ↑ Types

A run of an array, which a loop walks front to back.

%a
The element type.
items
The array.
from
The first index walked.
to
The index the walk stops before.

Made by in-array, which checks the bounds. Its cursor is an int.

See also: in-array

ReverseArraySlice

record ↑ Types

A run of an array, which a loop walks back to front.

%a
The element type.
items
The array.
from
The lowest index walked, the last visited.
to
The index above the first one visited.

Made by in-reverse-array, which checks the bounds. Its cursor is an int, starting at to minus 1.

See also: in-reverse-array

Map

type alias ↑ Types

A persistent, unordered hash map.

%k
The key type. Requires an Eq instance.
%v
The value type.
(def m #map(("one" 1) ("two" 2)))
(map-ref m "two")              ; 2
(map-ref (map-set m "one" 11) "one")   ; 11
(map-ref m "one")              ; 1, m is unchanged

A CHAMP trie (Compressed Hash-Array Mapped Prefix-tree) implementation (Map.Map in the runtime). Updates return a new persistent map sharing untouched subtrees with the original.

Key equality. Map constructors (map-empty, ->map, list->map, vec->map, the #map(...) literal, builder or transient constructors, and the mapping collector) require an Eq instance for the key type, using it for equality and hashing. Maps derived from an existing map retain its key comparer.

Order. Hash maps are unordered; iteration order is not guaranteed.

Entries. Callbacks for map-fold, map-filter, map-for-each and related functions receive the key and value as two separate arguments. An entry is represented as a (Tuple k v) pair when treated as a single value: in map->list, map->seq, map-cursor-current, map-find, and generic Iterable loops.

Two maps are = when they contain identical key-value pairs. A map implements Iterable, Collection, Refable, Settable, and Addable. Calling add on a map takes a pair and replaces any existing association for that key.

See also: map-empty, map-ref, map-set, map-remove, MapBuilder, TransientMap, Mapping

MapCursor

type alias ↑ Types

A cursor for iterating over a map.

%k
The key type of the map.
%v
The value type of the map.

Used by Iterable to walk a map. A cursor is a value: map-cursor-done? and map-cursor-current only read it, and map-cursor-next answers a cursor one entry on. A walk allocates nothing.

See also: map-cursor, map-cursor-done?, map-cursor-current, map-cursor-next

MapBuilder

type alias ↑ Types

A mutable buffer used to construct a map efficiently in a single pass.

%k
The key type.
%v
The value type.
(def b (mapbuilder-empty))
(mapbuilder-add! b "a" 1)
(mapbuilder-add! b "a" 2)
(mapbuilder-length b)   ; 2
(mapbuilder->map b)     ; #map((a 2))

An efficient builder for constructing maps in bulk. Insertions append to a flat buffer and are populated into the trie in a single pass when mapbuilder->map is called, avoiding intermediate tree copies.

A builder does not support lookup or removal. If duplicate keys are added, the last value wins. It implements Addable! with a pair and Collection reporting the number of entries appended.

See also: mapbuilder-empty, mapbuilder-add!, mapbuilder->map, TransientMap

TransientMap

type alias ↑ Types

A mutable in-place map for high-performance batch updates.

%k
The key type.
%v
The value type.
(def t (map->transientmap m))
(transientmap-set! t "c" 3)
(transientmap-remove! t "a")
(transientmap->map t)

Provides in-place variants of standard map operations: functions take the same arguments in the same order as their map- counterparts, and mutations return Unit.

A transient mutates modified trie nodes in place without copying, and transientmap->map freezes it back into an immutable map in O(1). The transient remains usable afterwards, with subsequent writes safely copying nodes.

Implements Addable! with a pair, and Collection.

See also: map->transientmap, transientmap->map, transientmap-set!, MapBuilder

Mapping

union ↑ Types

The collector that gathers (key value) pairs into a map.

%k
The key type. Collecting asks for its Eq.
%v
The value type.
mapping
The collector. Each element it is handed is a (Tuple k v).
(loop (:for (k v) pairs)
      (:acc m (mapping (Tuple k (* v 2)))))

Accumulates through a MapBuilder, so a key collected twice keeps the last value.

See also: list->map, MapBuilder

StringWalk

type alias ↑ Types

A step through a string’s characters: what (:for ch s) iterates with.

The cursor of a string’s Iterable impl. It is not a StringCursor: it takes the string’s bytes once and decodes each character as it steps onto it, where a cursor loop asks the string at every step whether it is a slice. So (:for ch s) is the fastest way through a string, and a cursor loop is for when the positions are wanted.

A walk holds the character it is on, and the next is decoded when it steps. It has no position to compare or to give to substring.

See also: string-walk, string-cursor-start

Stringing

union ↑ Types

The collector that gathers characters into a string.

stringing
Written in an :acc clause with the character to add.
(loop (:for c "hello")
      (:acc out (stringing (char-upcase c)))
      => out)                                  ; "HELLO"
{stringing c (:for c "a1b2") (:when (char-alphabetic? c))}   ; "ab"

Its accumulator is a StringBuilder, so collecting n characters costs the length of the result, where string-append in a loop copies the growing string every time.

See also: Collector, string->list

Encoding

type alias ↑ Types

A character encoding: a .NET System.Text.Encoding.

(text encodings) has one value for every encoding .NET knows, named as .NET names it in lower case (utf-8, utf-16be, windows-1252, dos-862), and finds one by name with encoding-named. What happens to bytes that do not decode is up to the operation, not the encoding: bytes->string is strict, a port is lenient.

See also: bytes->string, string->bytes

FsKind

union ↑ Types

What a path names, when it names anything.

FsFile
A file.
FsDirectory
A directory.

See also: FsInfo, file-info

FsInfo

record ↑ Types

Metadata returned by fs-info describing an existing path.

kind
A file or a directory.
size
In bytes. 0 for a directory.
modified-ms
The last write, in Unix milliseconds, UTC.
link?
Whether the path itself is a symbolic link.

Bundles all file attributes together to ensure atomic metadata queries.

For a link, size and modified-ms are those of what it leads to, and a link to nothing keeps its own. directory-walk and directory-delete-tree do not enter a directory that is a link.

Milliseconds because (std datetime)’s unix-milliseconds->instant takes them, and the prelude cannot name an Instant itself.

See also: file-info, fs-info, FsKind

MoveMode

union ↑ Types

What a move does when something is already at the target.

MoveNew
Fails, and changes nothing.
MoveReplace
A file at the target is replaced, in the one rename that moves the new one there.

With MoveReplace nothing ever sees the target missing. A directory is never replaced, whichever of the two it is.

See also: file-move, fs-move

InputPort

type alias ↑ Types

An input port: bytes, and text read from them.

One type for every input port, as in Racket: a file, a string, standard input, a socket, a pipe. A port is bytes. read-line, read-char and read-all decode UTF-8 from them, and read-some, read-bytes and peek-bytes from (std ports) take the bytes themselves; the two kinds of read mix freely on one port.

Decoding is lenient: a byte sequence that is not UTF-8 reads as U+FFFD. A byte order mark is not special, and reads as U+FEFF. Text in another encoding is read through reencode-input-port from (std ports).

A string port is a port over the string’s own UTF-8 bytes. Every port is buffered: port-eof? usually checks the buffer directly, and a read suspends inside a bjoroutine only when the buffer has to be refilled.

A read that is cancelled while it waits, by with-deadline or a cancelled scope, consumes nothing: the part of a line that had arrived stays in the port for the next read. Two fibers may read one port, and each line, character or byte goes to exactly one of them; which of them gets which is theirs to arrange. A failure of the underlying stream is reported to every read after it, once what arrived before it has been read.

It is also a .NET System.IO.TextReader, so a .NET API that takes one takes a port.

See also: open-input-file, open-input-string, read-line, read-char, port-eof?, close-input-port

OutputPort

type alias ↑ Types

An output port: bytes, and text written to them as UTF-8.

One type for every output port, as in Racket: a file, a string, standard output and error, a socket, a pipe. A port is bytes. write-string, write-char and writeln write UTF-8 to it, a string as the bytes it already is, and write-bytes! from (std ports) writes bytes as they are; the two mix freely on one port. No byte order mark is ever written. Text in another encoding is reencode-output-port’s.

A port buffers what is written to it, and a write that fills the buffer drains it, which is why writes have a suspending copy as well as flush. Standard output is buffered as Racket’s is: a line at a time on a terminal, a block at a time when redirected, and flushed when the program ends, when it panics and before it reads standard input. Standard error is not buffered.

Many fibers may write to one port at once: each write goes in whole. It is also a System.IO.TextWriter, so a .NET API that takes one takes a port, and its writes are UTF-8 on the port too.

See also: open-output-file, open-output-string, write-string, flush-port, close-output-port

WriteMode

union ↑ Types

How an output file is opened.

Truncate
Create the file, or empty it if it exists. The default.
Append
Create the file, or write after what it holds.
CreateNew
Create the file, and fail with an IOException if it exists. The check and the create are one system call, so of two writers racing for a path exactly one wins.

See also: open-output-file, call-with-output-file, open-write-stream

LineMode

union ↑ Types

What ends a line: Racket’s read-line modes.

Any
\n, \r or \r\n, the longest that matches. The default.
AnyOne
\n or \r, each on its own, so \r\n ends a line and then an empty one.
Linefeed
\n alone. A \r is part of the line.
Return
\r alone. A \n is part of the line.
ReturnLinefeed
\r\n alone. A \r or \n on its own is part of the line.

See also: read-line, read-line/opt, file-read-lines

PortReads

record ↑ Types

An iterable sequence wrapping a port and reader function, produced by in-port.

%a
The type of element yielded by the reader.
port
The port.
read
Reads the next element, returning None at end of input.

Its Iterable implementation calls read until it returns None.

See also: in-port

Duration

record ↑ Types

A fixed length of time: hours, minutes and seconds, not calendar days.

(with-deadline (seconds 5) (fetch url))
(displayed (minutes 90))   ;; "PT1H30M"

What every timer takes: timeout, with-deadline and with-shield. A number of milliseconds has its unit in no type, so 5000 is easy to misread, and a count that overflows becomes a different deadline without a word. A duration has its unit, and making one past its range raises.

Built on TimeSpan, and holds ±(263 − 1) ticks of 100 ns, about ±29 227 years. Ordered, and printed in ISO 8601: PT1H30M, -PT0.5S. (std datetime) adds the arithmetic and the calendar: duration, +duration, duration-between, iso8601->duration. A day there is exactly 24 hours; a calendar day is a DatePeriod.

A timer counts whole milliseconds. A part of a millisecond counts as a whole one, so a positive duration never reads as zero.

See also: seconds, timeout, with-deadline

Clock

record ↑ Types

Where the time comes from: a record of functions, so a program can make its own.

read-monotonic-ms
Milliseconds from an unspecified start. Never decreases; only differences mean anything.
read-monotonic-ns
The same clock in nanoseconds, at the resolution the clock has.
read-utc-ticks
The wall clock, in .NET ticks since 0001-01-01 UTC. May step back when the machine's time is corrected.
read-zone
The zone (std datetime)'s today is in.
advance-ticks
What (std datetime)'s clock-advance! calls, with a number of ticks. None for a clock that cannot be moved.

monotonic-ms and monotonic-ns read current-clock, and (std datetime)’s now and today read the same one, so binding it moves both.

See also: make-clock, current-clock, monotonic-ms, monotonic-ns

Functions

+

function ↑ Functions

(: + (-> %a %a %a))

The sum of two numbers.

a
The first addend.
b
The second, of the same type.
returns
a plus b. An integer sum that overflows wraps.
(+ 1 2)       ; 3
#fl(+ 1 2 3)     ; 6, folded from the left
(+)           ; 0

The C# operator, at any type with a Num implementation. Written with more than two operands it folds from the left; (+ x) is x and (+) is 0.

Nothing checks for overflow at run time: (+ n 1) at int 2147483647 is -2147483648. Widen first where a sum must not overflow. There is no implicit widening between variables, so an int and a double need a cast to be added.

See also: -, *, negate

-

function ↑ Functions

(: - (-> %a %a %a))

The difference of two numbers.

a
What to subtract from.
b
What to subtract, of the same type.
returns
a minus b. An integer difference that overflows wraps.
(- 10 3)      ; 7
#fl(- 10 3 2)    ; 5, folded from the left
(- 4)         ; -4, which is (negate 4)

The C# operator. With more than two operands it folds from the left. With one, it is negate, which keeps the operand’s type.

See also: +, negate

*

function ↑ Functions

(: * (-> %a %a %a))

The product of two numbers.

a
The first factor.
b
The second, of the same type.
returns
a times b. An integer product that overflows wraps.
(* 6 7)       ; 42
#fl(* 2 3 4)     ; 24
(*)           ; 1

The C# operator. With more than two operands it folds from the left; (* x) is x and (*) is 1.

See also: +, /

/

function ↑ Functions

(: / (-> %a %a %a))

The quotient of two numbers, truncated at an integer type.

a
The dividend.
b
The divisor, of the same type.
returns
a divided by b, rounded toward zero for integers.
raises System.DivideByZeroException
When b is an integer zero.
(/ 7 2)       ; 3
(/ 7.0 2.0)   ; 3.5
(/ 1.0 0.0)   ; infinity
#fl(/ 100 5 2)   ; 10

The C# operator. Integer division truncates and throws on a zero divisor; a constant integer divided by the literal 0 is refused at compile time. Double division by zero is infinite, and (/ 0.0 0.0) is NaN.

With more than two operands it folds from the left. With one, it is recip.

See also: %, recip, *

%

function ↑ Functions

(: % (-> %a %a %a))

The remainder of a division, with the sign of the dividend.

a
The dividend.
b
The divisor, of the same type.
returns
What is left of a after dividing by b.
raises System.DivideByZeroException
When b is an integer zero.
(% 7 2)       ; 1
(% -7 2)      ; -1, not 1
(% 7 -2)      ; 1

The C# operator: a remainder, not a modulus. The always-positive one is (% (+ (% a n) n) n).

See also: /

negate

function ↑ Functions

(: negate (-> %a %a))

A number with its sign flipped.

x
The number.
returns
Minus x, of x's own type.

(negate x) is the same as (- x), since (- x) expands to thi function. A primitive rather than (- 0 x), which would fix the type to that of the literal 0 and so refuse a double. It is C#’s unary minus, so negating the most negative integer of a type wraps to itself.

See also: -, recip

recip

function ↑ Functions

(: recip (-> %a %a))

The reciprocal of a number: one divided by it.

x
The number.
returns
1 divided by x, of x's own type.
(recip 4.0)   ; 0.25
(/ 4.0)       ; the same
(recip 4)     ; 0: integer division

What (/ x) expands to, emitted as 1 / x at x’s type. At an integer type that is integer division, so it is 0 for any x other than 1 and -1, and throws System.DivideByZeroException for 0.

See also: /, negate

sqrt

function ↑ Functions

The square root of a number.

x
The number. An integer argument is widened to a double.
returns
The non-negative square root, as a double. NaN for a negative x.
(sqrt 9)      ; 3.0
(sqrt 2.0)    ; 1.4142135623730951

System.Math.Sqrt. The rest of System.Math is in (std maths).

See also: *, recip

<

function ↑ Functions

(: < (-> %a %a bool))

Whether one number is less than another.

a
The first operand.
b
The second, of the same type.
returns
#t when a is less than b. #f when either is NaN.
(< 1 2)          ; #t
#ch(< 1 2 3)     ; #t: each is less than the next

The C# operator, at numbers, char and StringCursor: the types with an Ordered implementation. Not at string, which has no such operator; compare and less? order every comparable type, strings ordinally.

For chaining, use the #ch(< 1 2 3) hash extension, comparing each operand with the next. Comparisons follow IEEE, so one against NaN is #f whichever way round it is written.

See also: <=, >, >=, compare

<=

function ↑ Functions

(: <= (-> %a %a bool))

Whether one number is less than or equal to another.

a
The first operand.
b
The second, of the same type.
returns
#t when a is at most b. #f when either is NaN.

The C# operator, as < is. With more than two operands it chains.

See also: <, >=, at-most?

>

function ↑ Functions

(: > (-> %a %a bool))

Whether one number is greater than another.

a
The first operand.
b
The second, of the same type.
returns
#t when a is greater than b. #f when either is NaN.

The C# operator, as < is.

See also: >=, <, greater?

>=

function ↑ Functions

(: >= (-> %a %a bool))

Whether one number is greater than or equal to another.

a
The first operand.
b
The second, of the same type.
returns
#t when a is at least b. #f when either is NaN.

The C# operator, as < is.

See also: >, <=, at-least?

bitwise-and

function ↑ Functions

(: bitwise-and (-> %a %a %a))

The bits set in both of two integers.

a
The first integer.
b
The second, of the same type.
returns
a AND b, bit by bit.
(bitwise-and 12 10)   ; 8

C#’s &, at every integer type, signed and unsigned: the types with an Integral implementation. With more than two operands it folds from the left.

See also: bitwise-ior, bitwise-xor, bitwise-not

bitwise-ior

function ↑ Functions

(: bitwise-ior (-> %a %a %a))

The bits set in either of two integers.

a
The first integer.
b
The second, of the same type.
returns
a OR b, bit by bit.
(bitwise-ior 12 10)   ; 14

C#’s |, at every integer type.

See also: bitwise-and, bitwise-xor

bitwise-xor

function ↑ Functions

(: bitwise-xor (-> %a %a %a))

The bits set in exactly one of two integers.

a
The first integer.
b
The second, of the same type.
returns
a XOR b, bit by bit.
(bitwise-xor 12 10)   ; 6

C#’s ^, at every integer type.

See also: bitwise-and, bitwise-ior

bitwise-not

function ↑ Functions

(: bitwise-not (-> %a %a))

An integer with every bit flipped.

x
The integer.
returns
The complement of x, of x's type.
(bitwise-not 0)       ; -1

C#’s ~, at every integer type.

See also: bitwise-and, bitwise-xor

shift-left

function ↑ Functions

(: shift-left (-> %a int %a))

An integer’s bits moved toward the high end.

x
The integer to shift.
n
How many places. An int whatever x is, masked to x's width.
returns
x shifted left by n, zeroes filling in from the low end.
(shift-left 1 4)      ; 16
(shift-left 1 32)     ; 1, not 0: the count is masked

C#’s <<. C# masks the count to the operand’s width, so at an int a count of 32 shifts by 0.

See also: shift-right, shift-right-logical

shift-right

function ↑ Functions

(: shift-right (-> %a int %a))

An integer’s bits moved toward the low end, keeping the sign of a signed type.

x
The integer to shift.
n
How many places. An int whatever x is, masked to x's width.
returns
x shifted right by n.
(shift-right -16 2)   ; -4

C#’s >>: arithmetic on a signed type, copying the sign bit in, and logical on an unsigned one. The count is masked as for shift-left.

See also: shift-right-logical, shift-left

shift-right-logical

function ↑ Functions

(: shift-right-logical (-> %a int %a))

An integer’s bits moved toward the low end, zeroes filling in.

x
The integer to shift.
n
How many places. An int whatever x is, masked to x's width.
returns
x shifted right by n, with zeroes in the high bits whatever x's sign.
(shift-right-logical -1 28)   ; 15

C#’s >>>. The count is masked as for shift-left.

See also: shift-right, shift-left

int->string

function ↑ Functions

(: int->string (-> int string))
(int->string n)

The decimal text of an int, the same on every machine.

n
The number.
returns
Its digits, with an ASCII minus when negative.

Does not use the c# culture, where minus can come back with U+2212 MINUS SIGN. The result is guaranteed to round-trip through string->int.

See also: string->int, long->string, displayed

long->string

function ↑ Functions

(: long->string (-> long string))
(long->string n)

The decimal text of a long, the same on every machine.

n
The number.
returns
Its digits, with an ASCII minus when negative.

See also: int->string, displayed

decimal->string

function ↑ Functions

(: decimal->string (-> decimal string))
(decimal->string n)

The text of a decimal, the same on every machine.

n
The number.
returns
Its digits, with a point and the digits after it that the decimal holds.
(decimal->string 1.50M)   ; "1.50"

A decimal keeps its scale, so 1.50M and 1.5M are equal and write as “1.50” and “1.5”.

See also: double->string, string->decimal, displayed

bigint->string

function ↑ Functions

(: bigint->string (-> bigint string))
(bigint->string n)

The decimal text of a bigint, the same on every machine.

n
The number.
returns
All its digits, with an ASCII minus when negative.

See also: long->string, string->bigint, displayed

int128->string

function ↑ Functions

(: int128->string (-> int128 string))
(int128->string n)

The decimal text of an int128.

n
The number.
returns
Its digits, with an ASCII minus when negative.

See also: long->string, string->int128, displayed

uint128->string

function ↑ Functions

(: uint128->string (-> uint128 string))
(uint128->string n)

The decimal text of a uint128.

n
The number.
returns
Its digits.

See also: int128->string, string->uint128, displayed

byte->string

function ↑ Functions

(: byte->string (-> byte string))
(byte->string n)

The decimal text of a byte.

n
The number.
returns
Its digits, from 0 to 255.

See also: int->string, displayed

double->string

function ↑ Functions

(: double->string (-> double string))
(double->string n)

The text of a double, the same on every machine.

n
The number.
returns
The shortest text that reads back as the same double, with a point as the decimal separator.
(double->string 6.0)   ; "6"
(double->string 2.5)   ; "2.5"

.NET’s default formatting in the invariant culture, so it round-trips through string->double on any machine. A whole number has no point: 6.0 is written 6. Use (std fmt) when the shape of the output matters.

See also: string->double, int->string, displayed

number->string

function ↑ Functions

(: number->string (-> int string))
(number->string n)

The decimal text of an int, under the name R7RS uses.

n
The number.
returns
The string representation of n, identical to int->string.

Only for int. Other numeric types have their own conversions, or displayed.

See also: int->string, displayed

clr-string->string

function ↑ Functions

(: clr-string->string (-> System.String string))

A Bjolang string from a .NET System.String.

s
The .NET string. Null is allowed.
returns
The same text as a Bjolang string; the empty string for null.

A .NET member that takes or returns a System.String directly is converted at the call. This is for one nested in another type, such as a (Seq System.String).

See also: string->clr-string

written

function ↑ Functions

(: written (-> %a string))

The text a value is written as.

x
The value.
returns
Its written text.
(written "a")             ; "\"a\""
(written #\a)             ; "#\\a"
(written 21L)             ; "21L"
(written (list "a" 1))    ; "(\"a\" 1)"

See also: displayed, write-into

write-into

function ↑ Functions

(: write-into (-> %a StringBuilder void))

Adds the written text of a value to a builder.

x
The value.
b
The builder.

What a container calls on each element, so that a nested value is written into one builder.

See also: written, display-into

displayed

function ↑ Functions

(: displayed (-> %a string))

The text a value prints as.

x
The value.
returns
Its text, as print and println write it.
(displayed 42)                ; "42"
(displayed #\a)               ; "a"
(displayed (list 1 2 3))      ; "(1 2 3)"
(displayed [1 2])             ; "[1 2]"
(displayed (Some "x"))        ; "(Some x)"

See also: written, display-into, print, println

display-into

function ↑ Functions

(: display-into (-> %a StringBuilder void))

Adds the displayed text of a value to a builder.

x
The value.
b
The builder.

See also: displayed, write-into

elements-print-into

function ↑ Functions

(: elements-print-into (-> string %s string StringBuilder (-> %a StringBuilder void) void))
(elements-print-into open xs close b each)

Adds the elements of a collection to a builder, between two strings.

open
The text before the elements.
xs
The collection: any Iterable.
close
The text after the elements.
b
The builder.
each
Adds one element, such as write-into or display-into.
(impl (Written (Bag %a))
  (where (Written %a))
  (defun (write-into s b)
    (elements-print-into "#bag(" s ")" b (fun (x b) (write-into x b)))))

A space goes between two elements.

See also: entries-print-into, write-into, display-into

entries-print-into

function ↑ Functions

(: entries-print-into (-> string %s string StringBuilder (-> %k StringBuilder void) (-> %v StringBuilder void) void))
(entries-print-into open xs close b each-key each-value)

Adds the entries of a map to a builder, between two strings, each as (k v).

open
The text before the entries.
xs
Any Iterable of (Tuple k v).
close
The text after the entries.
b
The builder.
each-key
Adds one key.
each-value
Adds one value.

See also: elements-print-into

->str

function ↑ Functions

(: ->str (-> %a string))

Deprecated: use displayed, and implement Displayed or Written.

x
The value.
returns
What displayed gives.

An implementation of ->str is called by ->str only, not by displayed, println or an interpolation.

See also: displayed, written

print

function ↑ Functions

(: print (-> %a void))
(print x)

Writes a value’s text to the current output port.

x
The value, written through its displayed.

(display (displayed x)): no newline after it. The port is current-output-port, so parameterize redirects it.

See also: println, displayed, display

println

function ↑ Functions

(: println (-> %a void))
(println x)

Writes a value’s text to the current output port, then a newline.

x
The value, written through its displayed.
(println 42)          ; 42
(println [1 2 3])     ; [1 2 3]

(displayln (displayed x)). The port is current-output-port.

See also: print, displayed, displayln

ignore

function ↑ Functions

(: ignore (-> %a void))

Discards a value that would otherwise have to be used.

x
The value.
(ignore (map-try-ref m k))
(ignore (bjo (log-visit user)))   ; detaches the promise

The method of the Discard trait. An expression in statement position must evaluate to Unit; any other type (including a Result or a .NET method return value) will trigger a compiler error. Use ignore to explicitly discard unwanted values. For most types it does nothing.

On a Promise it is detach: the result is not wanted, but a failure inside the fiber is reported as unhandled rather than lost silently. A fiber that stopped because it was cancelled is not reported.

See also: unit, detach

make-box

function ↑ Functions

(: make-box (-> %a (Box %a)))
(make-box elem)

A new box holding a value.

elem
What it starts out holding.
returns
A box of its own.

See also: box-ref, box-set!

box-ref

function ↑ Functions

(: box-ref (-> (Box %a) %a))
(box-ref b)

What a box holds.

b
The box.
returns
The value most recently put in it.

See also: box-set!, deref

box-set!

function ↑ Functions

(: box-set! (-> (Box %a) %a Unit))
(box-set! box val)

Replaces what a box holds, in place.

box
The box.
val
Its new value.

See also: box-ref, make-box

ref

function ↑ Functions

(: ref (-> %c %index %out))

Looks up an element in a collection by index or key.

coll
The collection to index.
i
The lookup key or zero-based integer index.
returns
The element associated with i.
raises System.IndexOutOfRangeException
When coll is an Array or Vec and i is out of bounds.
raises System.Collections.Generic.KeyNotFoundException
When coll is a Map and i is not present.
(ref [10 20 30] 1)          ; 20
(ref #map("a" 1) "a")       ; 1

The primary method of the Refable trait, also used by get for nested path lookups.

Supported collections:

See also: try-ref, ref-set, get, vec-ref, map-ref

try-ref

function ↑ Functions

(: try-ref (-> %c %index (Option %out)))

Safely looks up an element by index or key, returning an Option.

coll
The collection to index.
i
The lookup key or integer index.
returns
(Some element) if present; None if the key is missing or index is out of bounds.
(try-ref [10 20 30] 5)      ; None
(try-ref #map("a" 1) "b")   ; None

A non-throwing lookup method on the Refable trait. Returns None when:

Note: for .NET Array, the default implementation calls ref, which will throw if the index is out of bounds.

See also: ref, try-get, map-try-ref

ref-set

function ↑ Functions

(: ref-set (-> %c %index %in %c))

Returns a copy of a persistent collection with an updated key or index.

coll
The persistent collection to update (unmodified).
i
The index or key to update.
x
The new value to associate with i.
returns
A new collection containing the updated value.
raises System.IndexOutOfRangeException
When coll is a Vec and i is out of bounds.
(ref-set [1 2 3] 0 9)       ; [9 2 3]
(ref-set #map("a" 1) "b" 2) ; #map(("a" 1) ("b" 2))

The method of the Settable trait, supporting persistent updates for Vec and Map. Also used by set and update when traversing nested key paths.

For a Vec, updating an existing index is O(log n); an out-of-range index throws. For a Map, sets an existing key or inserts a new one in O(log n).

See also: ref, set, update, vec-set, map-set

ref-set!

function ↑ Functions

(: ref-set! (-> %c %index %in void))

Writes a value at a key or index of a mutable collection, in place.

coll
The collection to write.
i
The index or key to write.
x
The value to put at i.
raises System.IndexOutOfRangeException
When coll is indexed by integer and i is out of bounds.
(def a (make-array 3 #:fill 0))
(ref-set! a 1 5)            ; a holds 0 5 0
(set! a 2 7)                ; the same write, through set!

The method of the Settable! trait, the write in place that goes with ref, as Addable! goes with Addable. set! with a path writes its last key through it.

Supported collections:

A persistent Vec or Map has no impl, because there is nothing to write in place: ref-set and set answer a copy.

See also: ref, ref-set, array-set!

deref

function ↑ Functions

(: deref (-> %a %out))

Returns the current value held in a cell, box, or parameter.

p
The cell or parameter.
returns
The value currently stored in p.

The primary method of the Derefable trait, implemented for Box (calling box-ref) and Param (calling parameter-ref). Also used by get when called without path steps.

See also: try-deref, box-ref, parameter-ref, get

try-deref

function ↑ Functions

(: try-deref (-> %a (Option %out)))

Returns the value held in a cell as an Option.

p
The cell or parameter.
returns
(Some value) if present, or None if the cell is empty.

The optional access method of the Derefable trait. The default implementation returns (Some (deref p)), which both Box and Param use.

See also: deref

deref-set!

function ↑ Functions

(: deref-set! (-> %a %in void))

Puts a new value in a cell, in place.

cell
The cell to write.
x
Its new value.
(def hits (make-box 0))
(deref-set! hits 1)
(set! hits 2)               ; the same write: hits is not a def/mutable
(get hits)                  ; 2

The method of the Derefable! trait, the write in place that goes with deref, as Settable! goes with Settable. Implemented for Box.

(set! name value) writes through it when name is not a def/mutable: the binding cannot change, so what it holds does. A def/mutable is written as a variable, whatever it holds.

A Param has no impl. It is given a value for an extent with parameterize, and is not written in place.

See also: deref, box-set!, ref-set!

Some

function ↑ Functions

(: Some (-> %a (Option %a)))

An Option holding a value.

v
The value.
returns
(Some v).

A case of the builtin Option, which marks presence or absence. It is a struct, so building one does not allocate.

See also: None, some?, option-ref, option-ref-or

some?

function ↑ Functions

(: some? (-> (Option %a) bool))

Whether an Option holds a value.

opt
The Option.
returns
#t for Some, #f for None.

See also: none?, option-ref

none?

function ↑ Functions

(: none? (-> (Option %a) bool))

Whether an Option is None.

opt
The Option.
returns
#t for None, #f for Some.

See also: some?

option-ref

function ↑ Functions

(: option-ref (-> (Option %a) %a))

The value inside a Some.

opt
The Option. Must be Some.
returns
The value it holds.
raises System.InvalidOperationException
When opt is None.

See also: option-ref-or, option-value, some?

option-ref-or

function ↑ Functions

(: option-ref-or (-> (Option %a) %a %a))

Returns the value inside an Option, or a fallback default for None.

opt
The Option.
fallback
The default value to return if opt is None. Eagerly evaluated.
returns
The value opt holds, or fallback.
(option-ref-or (map-try-ref settings "port") 8080)

See also: option-value, option-ref

option-value

function ↑ Functions

(: option-value (-> (Option %a) %a %a))
(option-value opt fallback)

Returns the value inside an Option, or a fallback default for None.

opt
The Option.
fallback
The default value to return if opt is None.
returns
The value opt holds, or fallback.

The same as option-ref-or, written in Bjolang with a match.

See also: option-ref-or

fst

function ↑ Functions

(: fst (-> (Tuple %a %b) %a))
(fst p)

The first item of a pair.

p
The pair.
returns
Its first item.
(fst (Tuple 1 "a"))             ; 1
(list-map fst (list (Tuple 1 "a") (Tuple 2 "b")))   ; (1 2)

For a pair only, as in F#. Take a longer tuple apart with a pattern: (def (a b c) t) or (match t ((Tuple a _ _) a)).

See also: snd

snd

function ↑ Functions

(: snd (-> (Tuple %a %b) %b))
(snd p)

The second item of a pair.

p
The pair.
returns
Its second item.
(snd (Tuple 1 "a"))   ; "a"

See also: fst

Ok

function ↑ Functions

(: Ok (-> %a (Result %e %a)))

A Result representing a successful computation.

v
The success value.
returns
(Ok v).

A constructor of the builtin (Result %e %a) type representing a successful value. Every #:exceptions interop call returns a Result. A module declaring its own Result type gets its own Ok and Err, which shadow these.

Like any value, a Result must be explicitly used: matched, propagated, or discarded with ignore.

See also: Err, ok?, result-map

Err

function ↑ Functions

(: Err (-> %e (Result %e %a)))

A Result representing a failure, holding an error value.

e
The error value.
returns
(Err e).
(match (open-input-file path)
  ((Ok port) (read-all port))
  ((Err e) (raise e)))

See also: Ok, err?, raise

grammar-checked

function ↑ Functions

(: grammar-checked (-> (Result string %a) %a))
(grammar-checked r)

The Ok value of a grammar’s check, for a literal the compiler checked.

r
What the check gave.
returns
The Ok value.

The compiler calls a check of a def/grammar on a literal when it compiles the literal, and refuses the literal on an Err. The program calls the check again when it runs, and this function takes the value out. The Err case calls panic!, and is reached only by a check that does not give the same result for the same value.

See also: panic!

ok?

function ↑ Functions

(: ok? (-> (Result %e %a) bool))
(ok? r)

Whether a Result is Ok.

r
The Result.
returns
#t for Ok, #f for Err.

See also: err?

err?

function ↑ Functions

(: err? (-> (Result %e %a) bool))
(err? r)

Whether a Result is Err.

r
The Result.
returns
#t for Err, #f for Ok.

See also: ok?

result-map

function ↑ Functions

(: result-map (-> (-?-> %a %b) (Result %e %a) (Result %e %b)))
(result-map f r)

Applies a transformation function to the value inside an Ok.

f
The function applied to the Ok value, returning a new value.
r
The Result to transform.
returns
(Ok (f v)) for (Ok v); returns an Err unchanged.
(result-map string-length (Ok "abc"))   ; (Ok 3)

To chain a function that itself returns a Result, use try-> instead.

f may be either colour. A step that waits has to be a (bjoroutine (x) ...); written (fun (x) ...), the same call selects the blocking copy and parks the fiber’s thread.

See also: ok?, Ok

make-parameter

function ↑ Functions

(: make-parameter (-> %a (Param %a)))

A new parameter: a value that parameterize rebinds for a dynamic extent.

v
Its value where nothing has bound it.
returns
A parameter, read with parameter-ref.
(: verbose? (Param bool))
(def verbose? (make-parameter #f))

(parameterize ((verbose? #t))
  (parameter-ref verbose?))   ; #t

A parameter is a value, not a function: it is read with parameter-ref, so (Param %a) is an ordinary type that can be passed, stored and returned.

The first 31 parameters made with make-parameter are cheap to read however many others exist. The count is shared by the whole program, the libraries it uses included: the prelude’s own effect operations take some of the 31. Past that, make-parameter makes a cold one, as make-cold-parameter does.

See also: parameter-ref, make-cold-parameter, deref

make-cold-parameter

function ↑ Functions

(: make-cold-parameter (-> %a (Param %a)))

A new parameter that gives up the cheapest kind of read.

v
Its value where nothing has bound it.
returns
A parameter, the same as make-parameter's in every other way.

For a parameter that is not read in a loop, so that it does not spend one of the 31 ids that stay cheap to read. Worth it for a parameter made per request or per connection rather than once at module level. Reading one costs nothing extra while it is the only cold parameter bound, and one more node access after that.

See also: make-parameter

parameter-ref

function ↑ Functions

(: parameter-ref (-> (Param %a) %a))

A parameter’s value where it is read.

p
The parameter.
returns
What the innermost parameterize bound it to, or its initial value.
(writeln (parameter-ref current-error-port) "failed")

See also: make-parameter, deref

parameter-push!

function ↑ Functions

(: parameter-push! (-> (Param %a) %a DynEnv))

Binds a parameter in the current dynamic environment; half of what parameterize expands to.

p
The parameter.
v
Its new value.
returns
The environment it displaced, for dyn-restore! to put back.

parameterize expands into a push, the body evaluation, and a dyn-restore! of the previous environment in a finally block. Not intended to be called directly.

See also: dyn-restore!, parameter-ref

eq?

function ↑ Functions

(: eq? (-> %a %a bool))

Whether two values are the same object.

a
The first.
b
The second.
returns
#t when a and b are one object; on a value type, when they are equal.

Object identity, for mutable cells, and not a substitute for =. A value type has no identity to ask about, so on one it compares as .NET’s default equality does. Keywords and symbols are interned, so on them it agrees with =.

See also: =, structural-equals

clr-eq

function ↑ Functions

(: clr-eq (-> %a %a bool))

C#’s == operator, private to std/eq.

a
The first.
b
The second.
returns
a == b.

What (std eq)’s Eq implementations for the primitive types are written with, so that = on them compiles to the operator. Refused in any module but std/eq: a type’s own Eq implementation is what .NET equality is made of, and writing one in terms of the other is a loop. Use =, or structural-equals.

See also: clr-equals, =

clr-equals

function ↑ Functions

(: clr-equals (-> %a %a bool))

.NET’s default equality, private to std/eq.

a
The first.
b
The second.
returns
The boolean result of EqualityComparer's Default.Equals.

Unlike clr-eq it compiles at a type variable, and it is reflexive on NaN, which is why the double implementation of = uses it. Refused in any module but std/eq, as clr-eq is.

See also: clr-eq, clr-hash, structural-equals

clr-hash

function ↑ Functions

(: clr-hash (-> %a int))

.NET’s default hash, private to std/eq.

a
The value.
returns
Its hash from EqualityComparer's Default; 0 for null.

The hash that goes with clr-equals, read through the same comparer. Refused in any module but std/eq.

See also: clr-equals, structural-hash

structural-equals

function ↑ Functions

(: structural-equals (-> %a %a bool))

Field-by-field equality, without the type’s own Eq.

a
The first.
b
The second.
returns
#t when both are of the same runtime type and every field is equal.
(impl (Eq Point)
  (defun (= a b) (structural-equals a b))
  (defun (eq-hash p) (structural-hash p)))

For an Eq implementation that wants the field-by-field comparison plus one tweak. It never consults the type’s own Equals, which is the implementation being written, so it does not loop; each field still compares through its own type’s equality.

Only a type that a Bjolang module declares is compared field by field. A string, a number, a List or any other type compares with its own equality, and an array element by element. The fields are found by reflection, those of base types included, and cached per type: an escape hatch, not a fast path.

See also: structural-hash, =, hash-combine

structural-hash

function ↑ Functions

(: structural-hash (-> %a int))

A hash over a value’s fields, without the type’s own Eq.

a
The value.
returns
A hash that agrees with structural-equals; 0 for null.

Folds the fields’ hashes in declaration order, and an array’s elements in order. A type that is compared with its own equality has its own hash. It agrees with structural-equals about what is equal, and is not the hash C# would have written bit for bit.

See also: structural-equals, hash-combine

hash-combine

function ↑ Functions

(: hash-combine (-> int int int))

Two hashes folded into one.

h1
The first hash.
h2
The second.
returns
A hash of the pair. Order matters.
(defun (eq-hash p) (hash-combine (eq-hash (record-ref p x))
                                 (eq-hash (record-ref p y))))

What an eq-hash over several fields folds with. System.HashCode.Combine, so (hash-combine a b) and (hash-combine b a) differ, and the value differs from one run of the program to the next.

See also: eq-hash, structural-hash

unhashable

function ↑ Functions

(: unhashable (-> string int))

The eq-hash of a type that has none: it throws, naming the type.

type-name
The type's name, for the message.
returns
Nothing: it always throws.
raises System.InvalidOperationException
Always, saying the type cannot be a Map or Set key.
(impl (Eq Counter)
  (defun (= a b) (structural-equals a b))
  (defun (eq-hash c) (unhashable "Counter")))

A record with a mutable field has no lawful hash: hashing the field breaks the rule that a key’s hash does not change, and leaving it out breaks the rule that equal values hash alike. type/derive writes this for such a type, and it is how a hand-written implementation says its type is not a key. It is loud rather than silent because the alternative is a Map that loses an entry the next time the field is written.

See also: hash-combine, eq-hash

eq-comparer

function ↑ Functions

(: eq-comparer (-> (System.Collections.Generic.IEqualityComparer %a)))

The .NET equality comparer that agrees with = at a type.

returns
An IEqualityComparer for the type the call is used at.
(defun (hashset-empty) (clr-hashset-empty (eq-comparer)))

Used when creating collections so that keys are compared using = and hashed using eq-hash. If the type’s own .NET equality matches Bjolang’s (which is almost always true), it returns .NET’s default comparer; otherwise, it delegates directly to the type’s Eq implementation.

See also: ord-comparer, =, eq-hash

ord-comparer

function ↑ Functions

(: ord-comparer (-> (System.Collections.Generic.IComparer %a)))

The .NET comparer that agrees with compare at a type.

returns
An IComparer for the type the call is used at.

The ordering counterpart of eq-comparer: returns .NET’s default comparer when the type’s CompareTo agrees with its Ord implementation, and delegates to Ord otherwise.

See also: eq-comparer, compare

raise

function ↑ Functions

(: raise (-> System.Exception %a))

Throws an exception, keeping the stack trace it already has.

e
The exception.
returns
Nothing: it never returns, so it fits where any type is wanted.
(match (parse s)
  ((Ok n) n)
  ((Err e) (raise e)))

The counterpart of try, which turns the failures it names into values: this is how one gets back out. An exception that was caught and is raised again keeps the stack trace of where it first failed.

Its result type is free because it never returns, so it can stand in a match arm whose siblings produce a value.

See also: Err, panic!

panic!

function ↑ Functions

(: panic! (-> string (#:exit-code int) %a))
(panic! msg #:exit-code 1)

Stops the program with a message.

msg
What went wrong, written to the error port.
#:exit-code
The process's exit code. 1 when not given.
returns
Nothing: it never returns, so it fits where any type is wanted.
(when (vec-empty? args)
  (panic! "usage: tool FILE" #:exit-code 2))

For a program that cannot go on. It writes msg and a newline to current-error-port, flushes it, and exits the process. No finally and no scope’s cleanup runs.

At the REPL it does not exit: it throws an exception of its own type, which the REPL reports as a panic.

See also: raise

iterable-start

function ↑ Functions

(: iterable-start (-> %s %cursor))

Returns a cursor positioned at the start of an iterable sequence.

s
The iterable collection or sequence.
returns
A cursor before or on the first element. Check iterable-done? before advancing.

One of the four methods (:for x s) is built on. A program may call them directly, but typically uses loop, fold, or comprehensions instead.

See also: iterable-done?, iterable-current, iterable-next

iterable-done?

function ↑ Functions

(: iterable-done? (-> %s %cursor bool))

Whether iteration has finished.

s
The iterable collection or sequence.
c
The cursor.
returns
#t if the iteration has completed or no element exists at c; #f otherwise.

Call once before each iterable-current. For Vec, Seq, and Map, this call advances the underlying enumerator: iterable-next returns the cursor passed to it, and calling iterable-done? twice advances past an element.

See also: iterable-start, iterable-current, iterable-next

iterable-current

function ↑ Functions

(: iterable-current (-> %s %cursor %elem))

The element at the current cursor position.

s
The iterable collection or sequence.
c
The cursor (after iterable-done? returned #f).
returns
The element at c.

See also: iterable-done?, iterable-next

iterable-next

function ↑ Functions

(: iterable-next (-> %s %cursor %cursor))

Returns the cursor for the next element.

s
The iterable collection or sequence.
c
The cursor.
returns
The cursor for the next element, or past-the-end.

For cursors that wrap an enumerator (such as Vec, Seq, and Map), this returns the cursor itself, while iterable-done? advances the position.

See also: iterable-start, iterable-done?

iterable-end

function ↑ Functions

(: iterable-end (-> %s %cursor void))

Ends a traversal that stops before iterable-done? returned #t.

s
The iterable collection or sequence.
c
The cursor.

A loop calls it on each cursor that it stops early: at a :finish, at an :abandon, or when another driver of the same level ends first. So find and any? over file-read-lines/seq close the file when they stop. Each cursor gets the call once at most. It may also be called after iterable-done? returned #t, and must then do nothing.

When an exception or a non-local exit leaves the loop, the loop calls iterable-cleanup instead. A cursor that holds a resource releases it in both.

The default does nothing. Implement it for a cursor that holds a resource for the traversal.

See also: iterable-start, iterable-done?

iterable-cleanup

function ↑ Functions

(: iterable-cleanup (-> %s %cursor void))

Releases what a cursor holds when an exception or a non-local exit leaves the loop.

s
The iterable collection or sequence.
c
The cursor that was live.

A loop calls it, in place of iterable-end, on each cursor that is live when an exception or a non-local exit (such as ret of a with-return) leaves the loop, inner levels first. A lazy seql whose consumer stops early calls it on the cursors it has open too. Each cursor gets the call once at most.

The default does nothing, and with it the loop has no try around it and keeps no record of its cursors. A cursor that holds a resource, such as an open file, releases it here as well as in iterable-end: a Seq does both, which disposes its enumerator, so a loop over file-read-lines/seq whose body raises closes the file.

See also: iterable-end

fold

function ↑ Functions

(: fold (-> (-> %elem %acc %acc) %acc %s %acc))

Combines every element of an iterable into one value, front to back.

f
The accumulator function: (f elem acc) returning the next accumulator.
acc
The initial value.
s
The iterable collection or sequence.
returns
The accumulated result, or acc if s is empty.
(fold + 0 '(1 2 3))                         ; 6
(fold (fun (x acc) (Cons x acc)) '() [1 2 3]) ; (3 2 1)

A loop, not a Seq: it runs at once. The callback is an ordinary function; seq-fold takes one that may suspend, over a Seq.

See also: seq-fold, for-each

map

function ↑ Functions

(: map (-> (-> %elem %b) %s (Seq %b)))

A lazy sequence of a function applied to each element.

f
The transformation function.
s
The iterable collection or sequence.
returns
A Seq of the transformed elements, in order.
(->list (map (fun (x) (* 2 x)) '(1 2 3)))   ; (2 4 6)

Returns a Seq regardless of s’s concrete collection type: elements are produced lazily as the sequence is evaluated, and f runs on each traversal. Use ->list or ->vec to collect results into a concrete data structure.

See also: filter, flat-map, ->list

filter

function ↑ Functions

(: filter (-> (-> %elem bool) %s (Seq %elem)))

A lazy sequence of the elements that satisfy a predicate.

f
The predicate function.
s
The iterable collection or sequence.
returns
A Seq of elements matching the predicate, in order.

See also: map, take-while

take

function ↑ Functions

(: take (-> int %s (Seq %elem)))

A lazy sequence of the first n elements.

n
The number of elements to take (0 or negative yields an empty sequence).
s
The iterable collection or sequence.
returns
A Seq of s's first n elements, or all elements if s contains fewer.

Stops after the n-th element without pulling additional elements from s, making it safe for endless sequences and stream ports.

See also: drop, take-while, first

drop

function ↑ Functions

(: drop (-> int %s (Seq %elem)))

A lazy sequence skipping the first n elements.

n
The number of elements to skip.
s
The iterable collection or sequence.
returns
A Seq of s without its first n elements; empty if s has no more than n elements.

See also: take, drop-while

take-while

function ↑ Functions

(: take-while (-> (-> %elem bool) %s (Seq %elem)))

A lazy sequence of elements taken while a predicate holds true.

f
The predicate function.
s
The iterable collection or sequence.
returns
A Seq of s's leading elements while (f x) is true.

See also: drop-while, take, filter

drop-while

function ↑ Functions

(: drop-while (-> (-> %elem bool) %s (Seq %elem)))

A lazy sequence skipping elements while a predicate holds true.

f
The predicate function.
s
The iterable collection or sequence.
returns
A Seq of s starting from the first element where (f x) returns #f.

Each traversal re-evaluates s from the start, skipping leading elements where f returns #t.

See also: take-while, drop

enumerate

function ↑ Functions

(: enumerate (-> %s (Enumerated %s)))
(enumerate s)

Each element of an iterable paired with its index, from 0.

s
The iterable collection or sequence.
returns
An (Enumerated %s): an iterable of (Tuple i x).
{listing (Tuple i c) (:for (Tuple i c) (enumerate "ab"))}   ; (0 a) (1 b)
(loop (:for (Tuple i x) (enumerate xs))
      (:when (> x 10))
      (:acc at (listing i)))                               ; where the big ones are

A struct around s, not a Seq. A loop over it at a known type walks s with an index beside its cursor, and allocates nothing: over an array, the loop reads it by index. Over a generic iterable it calls s’s methods through its dictionary.

Over a Seq, such as (map f xs), the adapter walks the sequence through its enumerator. seq-enumerate is a Seq itself, and fuses with a chain of seqls under it into one loop.

See also: zip, seq-enumerate, Enumerated, up-from

zip

function ↑ Functions

(: zip (-> %l %r (Zipped %l %r)))
(zip l r)

The elements of two iterables in pairs, until either ends.

l
The left iterable.
r
The right iterable.
returns
A (Zipped %l %r): an iterable of (Tuple x y).
{listing (str name "=" (displayed n)) (:for (Tuple name n) (zip names #[1 2 3]))}
(loop (:for (Tuple a b) (zip xs (drop 1 xs)))   ; each element and the next
      (:acc rises (counting (< a b))))

A struct around both, not a Seq: a loop over it at a known type walks the two cursors side by side and allocates nothing. The walk ends when either side ends, and the other side is ended then too, so a sequence that holds a file is closed. The left side is asked first: when the right side is the shorter, one more element of the left is read, and not used. The two may be of different types.

See also: enumerate, Zipped

in-cycle

function ↑ Functions

(: in-cycle (-> %s (Cycled %s)))
(in-cycle s)

The elements of an iterable, over and over.

s
The iterable collection or sequence. Walked again each time a walk of it ends.
returns
A (Cycled %s): an iterable of s's elements, without end unless s is empty.
(->list (take 5 (in-cycle '(1 2))))              ; (1 2 1 2 1)
{summing (* x w) (:for (Tuple x w) (zip #[5 6 7 8] (in-cycle '(1 -1))))}
; 5 - 6 + 7 - 8 = -2

It ends when a walk of s yields nothing, so the cycle of an empty iterable is empty rather than a loop that never yields. A sequence is started again for each walk, which runs its body again; a sequence over a port that is used up yields nothing the second time, and the cycle ends there. To cycle what such a sequence yields once, collect it first: (in-cycle (->vec s)) walks s once, then cycles the vec by index. ->vec reads all of s before the first element, so this is for a sequence that is finite and not too long.

A struct around s, as zip is, so a loop over it at a known type inlines it with what it wraps and allocates nothing. Its step asks s for the element after the current one before a loop does, so over a sequence with effects one element more is read than is used.

See also: zip, take, Cycled

pairwise

function ↑ Functions

(: pairwise (-> %s (Pairwise %s)))
(pairwise s)

Each element of an iterable with the one after it.

s
The iterable collection or sequence.
returns
A (Pairwise %s): an iterable of (Tuple a b), one fewer than s has, and none when s has fewer than two.
{summing 1 (:for (Tuple a b) (pairwise #[1 3 2 5 4])) (:when (< a b))}   ; 2
{listing (- b a) (:for (Tuple a b) (pairwise '(1 4 9 16)))}            ; (3 5 7)

One walk of s: (zip xs (drop 1 xs)) gives the same pairs and walks xs twice, which runs a sequence twice. The first element is read when the walk starts. A struct around s, as zip is, so a loop over it at a known type inlines it and allocates nothing.

See also: zip, enumerate, Pairwise

chain

function ↑ Functions

(: chain (-> %a %b (Chained %a %b)))
(chain a b)

The elements of one iterable, then those of another.

a
The first iterable.
b
The second iterable. Its elements are of the type a's are.
returns
A (Chained %a %b): an iterable of a's elements and then b's.
(->list (chain #[1 2] '(3 4)))                     ; (1 2 3 4)
{summing x (:for x (chain (range 0 3) [10 20]))}   ; 33

The two may be iterables of different kinds, an array and a list, without making either a sequence. A struct around both, as zip is, so a loop over it at a known type inlines it and allocates nothing. Its step on the first side asks it for the element after the current one before a loop does, so over a sequence with effects one element more is read than is used.

See also: zip, seq-append, Chained

in-repeat

function ↑ Functions

(: in-repeat (-> %a (#:times int) (Repeated %a)))
(in-repeat x #:times repeat-endless)

One value, over and over, or a given number of times.

x
The value.
#:times
How many times. Without it, without end. Zero or less gives nothing.
returns
A (Repeated %a): an iterable of x.
(->list (in-repeat 'a #:times 3))                  ; (a a a)
{listing (Tuple k v) (:for (Tuple k v) (zip '(x y) (in-repeat 0)))}
; each key with 0

Mostly a side of a zip, which ends with its other side. The cursor is a count, so a loop over it allocates nothing.

See also: in-cycle, zip, Repeated

seq-enumerate

function ↑ Functions

(: seq-enumerate (-> %s (Seq (Tuple int %elem))))

A lazy sequence of each element paired with its index, from 0.

s
The iterable collection or sequence.
returns
A Seq of (Tuple i x).
{summing i (:for (Tuple i x) (seq-enumerate (filter even? xs)))}

What enumerate was before it made an adapter. Its default is a seql, so a loop over it fuses with a chain of others under it, such as (seq-enumerate (map f xs)), into one loop. Over a collection, enumerate is as fast and allocates nothing.

See also: enumerate, map

flat-map

function ↑ Functions

(: flat-map (-> (-> %elem (Seq %b)) %s (Seq %b)))

A lazy sequence flattening the sub-sequences returned by a function.

f
A function taking each element and returning a Seq.
s
The iterable collection or sequence.
returns
A Seq concatenating the elements of each sequence returned by f.

See also: map, seq-append

any?

function ↑ Functions

(: any? (-> (-?-> %elem bool) %s bool))

Whether at least one element satisfies a predicate.

f
The predicate. It may suspend.
s
The iterable collection or sequence.
returns
#t if (f x) is true for any element; #f if none match or s is empty.

Stops at the first match; f is not called on subsequent elements.

See also: all?, find

all?

function ↑ Functions

(: all? (-> (-?-> %elem bool) %s bool))

Whether all elements satisfy a predicate.

f
The predicate. It may suspend.
s
The iterable collection or sequence.
returns
#t if (f x) is true for all elements (or s is empty); #f if any element returns false.

See also: any?, find

find

function ↑ Functions

(: find (-> (-?-> %elem bool) %s (Option %elem)))

Finds the first element that satisfies a predicate.

f
The predicate. It may suspend.
s
The iterable collection or sequence.
returns
(Some x) for the first element satisfying f; None otherwise.

See also: any?, filter

for-each

function ↑ Functions

(: for-each (-> (-?-> %elem void) %s void))

Calls a function on each element for its side effects.

f
The procedure to call. It may suspend.
s
The iterable collection or sequence.

See also: fold, seq-for-each

->list

function ↑ Functions

(: ->list (-> %s (List %elem)))

An iterable’s elements as a list.

s
The iterable collection or sequence, walked to the end.
returns
A list of its elements, in order. Passing a list returns the list itself.

The default is a loop, so (->list (map f xs)) walks xs once and makes no sequence between the two.

See also: ->vec, ->seq

->vec

function ↑ Functions

(: ->vec (-> %s (Vec %elem)))

An iterable’s elements as a vec.

s
The iterable collection or sequence, walked to the end.
returns
A vec of its elements, in order. Passing a vec returns the vec itself.

See also: ->list, ->seq

->map

function ↑ Functions

(: ->map (-> %s (Map %k %v)))
(->map s)

An iterable of key and value pairs as a map.

s
The iterable collection or sequence of (Tuple key value), walked to the end.
returns
A map of the pairs. A later key replaces an earlier one that is equal to it.
(->map (enumerate "ab"))   ; #map((0 #\a) (1 #\b))

Not an Iterable method, since its where clause says the element is a pair. It is copied into its call, so (->map (map f xs)) walks xs once and makes no sequence.

See also: ->list, ->vec, list->map

count

function ↑ Functions

(: count (-> %s int))

How many elements an iterable yields.

s
The iterable collection or sequence.
returns
The number of elements.

A vec, an array and a map answer their length. Anything else is walked to the end: over a source with effects that is a consumption, so the count of a port->seq reads the port.

See also: length, first

first

function ↑ Functions

(: first (-> %s (Option %elem)))

The first element of an iterable, if it has one.

s
The iterable collection or sequence.
returns
(Some x) for the first element; None when s is empty.

Pulls one element and no more, so it is safe on an endless sequence.

See also: find, take

->seq

function ↑ Functions

(: ->seq (-> %s (Seq %elem)))

Converts an iterable into a lazy sequence.

s
The iterable collection or sequence.
returns
A Seq of s's elements, in order. Passing a Seq returns the sequence itself.

See also: ->list, ->vec, list->seq, vec->seq

cursor-start

function ↑ Functions

(: cursor-start (-> %s %cursor))

Returns a cursor positioned at the first element.

s
The collection.
returns
A cursor; at the end if s is empty.

See also: cursor-end, cursor-next

cursor-end

function ↑ Functions

(: cursor-end (-> %s %cursor))

Returns a cursor positioned past the last element.

s
The collection.
returns
The cursor after the last element: the terminating boundary.

See also: cursor-end?, cursor-prev

cursor-end?

function ↑ Functions

(: cursor-end? (-> %s %cursor bool))

Whether a cursor has reached the terminating boundary.

s
The collection.
c
The cursor.
returns
#t if at the past-the-end position; #f otherwise.

See also: cursor-end, cursor-ref

cursor-ref

function ↑ Functions

(: cursor-ref (-> %s %cursor %elem))

The element at the current cursor position.

s
The collection.
c
The cursor. Must not be at the end.
returns
The element at c.

See also: cursor-end?, string-cursor-ref

cursor-next

function ↑ Functions

(: cursor-next (-> %s %cursor %cursor))

Returns the cursor for the next element.

s
The collection.
c
The cursor.
returns
The cursor after c.

See also: cursor-prev, cursor-end?

cursor-prev

function ↑ Functions

(: cursor-prev (-> %s %cursor %cursor))

Returns the cursor for the previous element.

s
The collection.
c
The cursor.
returns
The cursor before c.

See also: cursor-next, cursor-start

collector-init

function ↑ Functions

(: collector-init (-> %c %acc))

The accumulator a collector starts from.

c
The collector.
returns
The empty accumulator.

See also: collector-step, collector-finish

collector-step

function ↑ Functions

(: collector-step (-> %c %acc %elem %acc))

An accumulator with one more value taken in.

c
The collector.
acc
The accumulator so far.
x
The value to take in.
returns
The updated accumulator. A mutable builder-backed collector modifies in place and returns the same builder.

See also: collector-init, collector-finish

collector-finish

function ↑ Functions

(: collector-finish (-> %c %acc %out))

What a collector delivers from its accumulator.

c
The collector.
acc
The accumulator, after the last step.
returns
The finished value: a list for listing, a sum for summing, and so on.

See also: collector-init, collector-step

length

function ↑ Functions

(: length (-> %a int))

How many elements a collection holds.

c
The collection.
returns
The number of elements: characters for a string, pairs for a map.

A method of the Collection trait, implemented in the prelude for List, Array, Vec, Map, Range, string, Seq and the builders and transients (VecBuilder, ListBuilder, MapBuilder, TransientMap), and in their own modules for the sets and ordered collections.

A List is walked to count it. A string is too, since it counts characters, which is string-count rather than string-length. A Seq is walked, which for one over a port or a file is reading it to the end. A Range’s is computed from its bounds and step.

See also: empty?, count

empty?

function ↑ Functions

(: empty? (-> %a bool))

Whether a collection holds nothing.

c
The collection.
returns
#t when it has no elements.

For a Seq this starts a walk and pulls at most one element. For a Range it compares the bounds only: lo not below hi.

See also: length, seq-empty?

add

function ↑ Functions

(: add (-> %coll %elem %coll))

A new collection with one more element.

coll
The collection, which is left as it was.
x
The element. For a map, a pair (k . v).
returns
The new collection.

A method of the persistent Addable trait. A Vec appends at the end. A Map has set semantics: a key already there takes the new value; map-add, which refuses a duplicate, keeps its own name. The sets and ordered collections implement it in their own modules, where adding an element already present changes nothing.

List has no implementation: a cheap add would prepend, and an in-order one costs a walk per element. Build one with a ListBuilder.

See also: add-all, add!, vec-add, map-set

add-all

function ↑ Functions

(: add-all (-> %coll %s %coll))

A new collection with all elements from an iterable added.

coll
The persistent collection to add to (unmodified).
xs
An Iterable whose elements match coll's element type.
returns
The new collection, with xs's elements added in order.
(add-all [1 2] '(3 4))   ; [1 2 3 4]

The default implementation calls add once per element. The element type of xs must match the collection’s element type.

See also: add, add-all!

add!

function ↑ Functions

(: add! (-> %coll %elem void))

Adds an element to a builder or transient, in place.

coll
The builder or transient.
x
The element. For a map-shaped one, a pair (k . v).

A method of Addable!, the trait over every mutable sink, so that filling a collection does not care which one it fills. The prelude implements it for VecBuilder, ListBuilder, StringBuilder (whose element is a char), MapBuilder and TransientMap; the set and ordered-collection builders and transients implement it in their own modules.

See also: add-all!, add

add-all!

function ↑ Functions

(: add-all! (-> %coll %s void))

Adds everything an iterable yields to a builder or transient, in place.

coll
The builder or transient.
xs
An Iterable whose elements match coll's element type.

In the order xs yields them. The source may be a List, a Vec, a Range, a string or a Map, or anything else Iterable; an element type that does not match the sink’s is refused at the call.

See also: add!, add-all

range

function ↑ Functions

(: range (-> int int Range))
(range lo hi)

The integers from lo up to but not including hi.

lo
The first integer, included.
hi
The bound, not included. At or below lo, the range is empty.
returns
A Range with step 1.
{listing i (:for i (range 0 4))}   ; (0 1 2 3)

See also: range-by, up-from, seq-range

range-by

function ↑ Functions

(: range-by (-> int int int RangeBy))
(range-by lo hi by)

Every by-th integer from lo up to but not including hi.

lo
The first integer, included.
hi
The bound, not included.
by
The positive step size. Must be greater than zero.
returns
A RangeBy. A walk of it stops at hi also when hi is near int-max.
{listing i (:for i (range-by 0 10 3))}   ; (0 3 6 9)

See also: range, up-from, down-from

up-from

function ↑ Functions

(: up-from (-> %n (#:to %n) (#:by %n) (UpFrom %n)))
(up-from from #:to (num-top) #:by 1)

The ints counting up from a start, with or without a bound.

from
The first int.
#:to
Where to stop, not included. Defaults to int-max.
#:by
The positive step.
returns
An iterable sequence for (:for ...) loops.
(loop (:for i (up-from 0))          ; no #:to: the port running out ends it
      (:for line (in-port p (fun (q) (read-line/opt q))))
      (:do (println (Tuple i line))))

range written the way a loop reads. (up-from 0 #:to n) is the indices of something of length n. Without #:to it is what :finish, :final and :until-cancelled end.

A #:by of zero or less is a panic, since the walk would never move. The struct is a value, so a loop over one allocates nothing for it.

See also: down-from, range, int-max

down-from

function ↑ Functions

(: down-from (-> %n (#:to %n) (#:by %n) (DownFrom %n)))
(down-from from #:to (num-bottom) #:by 1)

The ints counting down from a start, with or without a bound.

from
The first int.
#:to
Where to stop, included. Defaults to int-min.
#:by
The distance to subtract each step. Positive.
returns
An iterable sequence for (:for ...) loops.
{listing i (:for i (down-from 3 #:to 0))}   ; (3 2 1 0)

Unlike up-from’s, its #:to is included: (down-from n #:to 0) counts down to zero and says zero. #:by is a distance, positive here too; zero or less is a panic.

See also: up-from, range, int-min

seq-empty

function ↑ Functions

(: seq-empty (-> (Seq %a)))

The empty sequence.

returns
A Seq with no elements.

See also: seq-empty?, seq-unfold

seq-empty?

function ↑ Functions

(: seq-empty? (-> (Seq %a) bool))

Whether a sequence has no elements.

s
The sequence.
returns
#t when it yields nothing.

Starts a walk of s and pulls at most one element, so over a source with effects it runs them as far as that element.

See also: first, empty?

seq-head

function ↑ Functions

(: seq-head (-> (Seq %a) %a))

Deprecated: use first. The first element of a sequence.

s
The sequence. Not empty.
returns
The first element it yields.
raises System.InvalidOperationException
When s is empty.

first takes any iterable, and answers (Some x), or None for an empty one. A use of seq-head warns, and it goes in a later release. There is no seq-tail, since a Seq has no rest to step to; (drop 1 s) is the sequence without its first element.

See also: first

seq-map

function ↑ Functions

(: seq-map (-> (-> %a %b) (Seq %a) (Seq %b)))

Deprecated: use map. A sequence of a function applied to each element, lazily.

f
The function.
s
The sequence.
returns
A Seq of the transformed elements, evaluated as pulled.

map takes any iterable and does the same to a sequence. A use of seq-map warns, and it goes in a later release.

See also: map

seq-filter

function ↑ Functions

(: seq-filter (-> (-> %a bool) (Seq %a) (Seq %a)))

Deprecated: use filter. A sequence of the elements that satisfy a predicate, lazily.

f
The predicate.
s
The sequence.
returns
A Seq of the elements where (f x) is true.

filter takes any iterable and does the same to a sequence. A use of seq-filter warns, and it goes in a later release.

See also: filter

seq-take

function ↑ Functions

(: seq-take (-> (Seq %a) int (Seq %a)))

Deprecated: use take. A sequence of the first n elements, lazily.

s
The sequence.
n
How many. Zero or less gives the empty sequence.
returns
A Seq of s's first n elements, or all of them if it has fewer.

(take n s) takes any iterable and does the same to a sequence. Its arguments are in the other order. A use of seq-take warns, and it goes in a later release.

See also: take

seq-drop

function ↑ Functions

(: seq-drop (-> (Seq %a) int (Seq %a)))

Deprecated: use drop. A sequence without its first n elements, lazily.

s
The sequence.
n
How many to skip. Zero or less skips none.
returns
A Seq of what follows; empty when s has no more than n.

(drop n s) takes any iterable and does the same to a sequence. Its arguments are in the other order. A use of seq-drop warns, and it goes in a later release.

See also: drop

seq-unfold

function ↑ Functions

(: seq-unfold (-> (-> %s (Option (Tuple %a %s))) %s (Seq %a)))

A sequence generated from a state, lazily.

f
Maps a state to (Some (Tuple x next-state)), the next element and the state after it, or to None to end.
state
The first state.
returns
A Seq of the elements f produces, until it returns None.
(take 5 (seq-unfold (fun (n) (Some (Tuple n (* 2 n)))) 1))
; 1 2 4 8 16

See also: seq-range, seq-empty

seq-range

function ↑ Functions

(: seq-range (-> int int (Seq int)))

The ints from start up to but not including stop, as a sequence.

start
The first, included.
stop
The bound, not included. At or below start, the sequence is empty.
returns
A lazy Seq of ints.

See also: range, seq-unfold

seq-append

function ↑ Functions

(: seq-append (-> (Seq %a) (Seq %a) (Seq %a)))

One sequence followed by another, lazily.

s1
The first.
s2
The second, walked once s1 is exhausted.
returns
A Seq of s1's elements, then s2's.

See also: flat-map

seq-length

function ↑ Functions

(: seq-length (-> (Seq %a) int))

Deprecated: use count. How many elements a sequence yields.

s
The sequence.
returns
The count.

count takes any iterable, and fuses with a chain under it. A use of seq-length warns, and it goes in a later release.

See also: count

seq->list

function ↑ Functions

(: seq->list (-> (Seq %a) (List %a)))

Deprecated: use ->list. A sequence’s elements as a list.

s
The sequence, walked to the end.
returns
A list of its elements, in order.

->list takes any iterable, and fuses with a chain under it. A use of seq->list warns, and it goes in a later release.

See also: ->list

seq->vec

function ↑ Functions

(: seq->vec (-> (Seq %a) (Vec %a)))

Deprecated: use ->vec. A sequence’s elements as a vec.

s
The sequence, walked to the end.
returns
A vec of its elements, in order.

->vec takes any iterable, and fuses with a chain under it. A use of seq->vec warns, and it goes in a later release.

See also: ->vec

seq-fold

function ↑ Functions

(: seq-fold (-> (-?-> %a %b %b) %b (Seq %a) %b))
(seq-fold f init s)

Combines every element of a sequence into one value, front to back.

f
Called with an element and the current accumulator; returns the next value. It may suspend.
init
The value to start from.
s
The sequence.
returns
The final accumulated value, or init when s is empty.

Eager, unlike the sequence builtins, so its callback may be of either colour: it runs here, not wherever the sequence is pulled.

See also: fold, seq-for-each

seq-for-each

function ↑ Functions

(: seq-for-each (-> (-?-> %a Unit) (Seq %a) Unit))
(seq-for-each f s)

Calls a function on each element of a sequence, for its effect.

f
The function. It may suspend.
s
The sequence.

See also: for-each, seq-fold

seq-cursor

function ↑ Functions

(: seq-cursor (-> (Seq %a) (SeqCursor %a)))

A cursor for one traversal of a sequence.

s
The sequence.
returns
A cursor holding a fresh enumerator of s.

What Iterable’s implementation for Seq traverses with. Holding the enumerator allows each element to be evaluated once, rather than re-evaluating earlier elements. The cursor is stateful and consumed during iteration; create a new cursor for repeated traversals.

See also: seq-cursor-done?, seq-cursor-current

seq-cursor-done?

function ↑ Functions

(: seq-cursor-done? (-> (SeqCursor %a) bool))

Advances a seq cursor to its next element, returning #t if exhausted.

c
The cursor.
returns
#t when the sequence is exhausted; #f if an element is available.

Advances the cursor: call once before each seq-cursor-current. When it returns #t, the sequence is exhausted and the underlying enumerator is disposed, closing any underlying file or stream resources. Calling it again continues to return #t.

See also: seq-cursor, seq-cursor-current

seq-cursor-current

function ↑ Functions

(: seq-cursor-current (-> (SeqCursor %a) %a))

The element at the current seq cursor position.

c
The cursor, after seq-cursor-done? returned #f.
returns
The element.

See also: seq-cursor-done?

seq-cursor-end

function ↑ Functions

(: seq-cursor-end (-> (SeqCursor %a) void))

Ends a traversal before the sequence is exhausted.

c
The cursor.

Disposes the underlying enumerator, which closes a file or stream that the sequence opened for this traversal. A loop calls it, through iterable-end, when it stops before the end. After the first call, and after seq-cursor-done? returned #t, it does nothing.

See also: seq-cursor, seq-cursor-done?

Cons

function ↑ Functions

(: Cons (-> %a (List %a) (List %a)))

A list with one more element in front.

x
The new first element.
xs
The list it goes in front of, which is shared, not copied.
returns
A list whose head is x and whose tail is xs.
(Cons 1 (Cons 2 Nil))   ; (1 2)

(match xs
  (Nil 0)
  ((Cons h _) h))

One of the two cases of a list, with Nil. Also used in pattern matching to deconstruct a non-empty list: (Cons h t). cons is the same function under a lower-case name.

See also: cons, Nil, list, list-head, list-tail

cons

function ↑ Functions

(: cons (-> %a (List %a) (List %a)))

A list with one more element in front.

x
The new first element.
xs
The list it goes in front of, which is shared, not copied.
returns
A list whose head is x and whose tail is xs.
(cons 0 (list 1 2))   ; (0 1 2)

The same as Cons. Only one cell is allocated: a list is immutable, so the new list and xs share every cell of xs.

See also: Cons, list, list-empty

list

function ↑ Functions

(: list (-> (Array %a) (List %a)))

A list of the arguments, in the order they are given.

items ...
The elements. None makes the empty list.
returns
A new list of items.
(list 1 2 3)   ; (1 2 3)
(list)         ; ()

Taken as a value, as in (def f list), it is the function from an Array of elements to a list.

See also: cons, Nil, list->vec

list-empty

function ↑ Functions

(: list-empty (-> (List %a)))

The empty list.

returns
The same list as Nil.

See also: Nil, list-empty?

list-head

function ↑ Functions

(: list-head (-> (List %a) %a))

The first element of a list.

xs
The non-empty list.
returns
Its first element.
raises System.InvalidOperationException
When xs is empty.

See also: list-tail, list-empty?, Cons

list-tail

function ↑ Functions

(: list-tail (-> (List %a) (List %a)))

A list without its first element.

xs
The non-empty list.
returns
The list following the first element (shares structural tail of xs).
raises System.InvalidOperationException
When xs is empty.

See also: list-head, over-list

list-empty?

function ↑ Functions

(: list-empty? (-> (List %a) bool))

Whether a list has no elements.

xs
The list.
returns
#t for Nil, #f for any other list.

See also: Nil, list-length

list-length

function ↑ Functions

(: list-length (-> (List %a) int))

How many elements a list has.

xs
The list.
returns
The number of elements, 0 for the empty list.

O(n): a list stores no count, so this walks it. To ask only whether a list is empty, list-empty? costs nothing.

See also: list-empty?, listbuilder-length

list-ref

function ↑ Functions

(: list-ref (-> (List %a) int %a))

The element at an index of a list.

xs
The list.
i
The index, from 0. Not negative, and less than the length.
returns
The element at i.
raises System.ArgumentOutOfRangeException
When i is negative, or not less than the length of xs.

O(i): it walks from the front. For many lookups by index, convert with list->vec first.

See also: list-head, list->vec

list-reverse

function ↑ Functions

(: list-reverse (-> (List %a) (List %a)))

A list’s elements in the opposite order.

xs
The list to reverse.
returns
A new list, last element first.

See also: list-foldr

list-append

function ↑ Functions

(: list-append (-> (List %a) (List %a) (List %a)))
(list-append xs ys)

One list followed by another.

xs
The elements that come first. They are copied.
ys
The elements that come after. They are shared, not copied.
returns
A list of xs's elements and then ys's.
(list-append (list 1 2) (list 3))   ; (1 2 3)

O(n) in the length of xs, and independent of ys: the result’s last cells are ys itself.

See also: cons, list-foldr

list-map

function ↑ Functions

(: list-map (-> (-?-> %a %b) (List %a) (List %b)))
(list-map f xs)

Applies a function to each element of a list.

f
The transformation function. May suspend.
xs
The list to map over.
returns
A new list of mapped values, in xs's order.
(list-map (fun (x) (* x x)) (list 1 2 3))   ; (1 4 9)

f is called on the elements in order, from the first.

See also: list-filter, list-for-each, list-foldl

list-filter

function ↑ Functions

(: list-filter (-> (-?-> %a bool) (List %a) (List %a)))
(list-filter keep? xs)

The elements of a list that satisfy a predicate.

keep?
The predicate function, returning #t to keep an element. May suspend.
xs
The list to filter.
returns
A new list containing elements that satisfied the predicate, in xs's order.
(list-filter (fun (x) (> x 1)) (list 1 2 3))   ; (2 3)

See also: list-map

list-foldl

function ↑ Functions

(: list-foldl (-> (-?-> %a %b %b) %b (List %a) %b))
(list-foldl f init xs)

Combines a list’s elements into one value, from the first.

f
Accumulator function taking (element, acc) and returning the next value. May suspend.
init
The initial accumulator value.
xs
The list to fold.
returns
The value returned by f after the last element, or init when xs is empty.
(list-foldl cons Nil (list 1 2 3))   ; (3 2 1)

f takes the element first and the accumulator second, the same order as list-foldr and fold.

See also: list-foldr, list-for-each

list-foldr

function ↑ Functions

(: list-foldr (-> (-?-> %a %b %b) %b (List %a) %b))
(list-foldr f init xs)

Combines a list’s elements into one value, from the last.

f
Accumulator function taking (element, acc) and returning the next value. May suspend.
init
The initial accumulator value.
xs
The list to fold.
returns
The value returned by f after the first element, or init when xs is empty.
(list-foldr cons Nil (list 1 2 3))   ; (1 2 3)

It reverses xs and folds that from the front, so a long list uses no stack, at the cost of one reversed copy.

See also: list-foldl, list-append

list-for-each

function ↑ Functions

(: list-for-each (-> (-?-> %a Unit) (List %a) Unit))
(list-for-each f xs)

Calls a function on each element of a list, for its effect.

f
The function. It may suspend.
xs
The list, walked from the first element.

See also: list-map, list-foldl

list-unfold

function ↑ Functions

(: list-unfold (-> (-?-> %s (Option (Tuple %a %s))) %s (List %a)))
(list-unfold f state)

A list generated from a state.

f
Maps a state to (Some (Tuple x next-state)), the next element and the state after it, or to None to end. May suspend.
state
The first state.
returns
A list of the elements f produces, in order, until it returns None.
(list-unfold (fun (n) (if (< n 5) (Some (Tuple (* n n) (+ n 1))) None)) 0)
; (0 1 4 9 16)

;; Pairs from a list, the odd one left over on its own.
(list-unfold (fun (xs)
               (match xs
                 ((Cons a (Cons b more)) (Some (Tuple (list a b) more)))
                 ((Cons a Nil) (Some (Tuple (list a) Nil)))
                 (Nil None)))
             (list 1 2 3 4 5))
; ((1 2) (3 4) (5))

Eager: f is called until it returns None, so an f that never does never returns. For an endless or partly read generation, use seq-unfold.

See also: seq-unfold, list-foldl

list->vec

function ↑ Functions

(: list->vec (-> (List %a) (Vec %a)))
(list->vec lst)

A vec of a list’s elements, in the same order.

lst
The list.
returns
A new vec.

See also: list->seq, list-ref

list->seq

function ↑ Functions

(: list->seq (-> (List %a) (Seq %a)))

A list seen as a sequence.

xs
The list.
returns
A seq of xs's elements, in order.

Nothing is copied: the seq is the list itself, and walking it walks the list. Since the list is immutable, it can be walked any number of times.

See also: list->vec, listbuilder-add-range!

list->string

function ↑ Functions

(: list->string (-> (List char) string))
(list->string cs)

A string of a list’s characters.

cs
The characters, in order.
returns
A new string.

See also: displayed

list->str

function ↑ Functions

(: list->str (-> (List %a) string))
(list->str l)

Deprecated: use displayed. A list written out as (1 2 3).

l
The list. Each element is formatted by its own displayed.
returns
The elements between parentheses, separated by one space: () for the empty list.
(displayed (list 1 2 3))             ; "(1 2 3)"
(displayed (list (list 1) (list 2)))  ; "((1) (2))"

No quote is written in front, and a string element is written as it is, without quotes. It is what displayed gives for a list.

See also: list->string, displayed

reader->list

function ↑ Functions

(: reader->list (-> Bjolang.Runtime.BjoInputPort (List string)))

The lines a reader has left, as a list.

r
The reader. It is read to its end and not closed.
returns
Each line without its line ending, in order.

It blocks the thread until the reader is out of lines.

See also: list->vec

listbuilder-empty

function ↑ Functions

(: listbuilder-empty (-> (ListBuilder %a)))

A new builder, empty, for making a list from the front to the back.

returns
A builder with no elements.
(def b (listbuilder-empty))
(listbuilder-add! b 1)
(listbuilder-add! b 2)
(listbuilder->list b)   ; (1 2)

Adding to a builder appends in O(1), which consing cannot do: the alternative is to cons onto the front and reverse at the end.

See also: listbuilder-add!, listbuilder->list, list->builder

list->builder

function ↑ Functions

(: list->builder (-> (List %a) (ListBuilder %a)))

A new builder holding a copy of a list’s elements.

xs
The list, which later changes to the builder do not touch.
returns
A builder with xs's elements, in order.

See also: list->listbuilder, listbuilder-empty

list->listbuilder

function ↑ Functions

(: list->listbuilder (-> (List %a) (ListBuilder %a)))

A new builder holding a copy of a list’s elements.

xs
The list, which later changes to the builder do not touch.
returns
A builder with xs's elements, in order.

The same as list->builder.

See also: list->builder

listbuilder-add!

function ↑ Functions

(: listbuilder-add! (-> (ListBuilder %a) %a void))

Adds an element to the end of a builder, in place.

b
The builder.
x
The element.
raises System.InvalidOperationException
When b has already been made into a list.

See also: listbuilder-add-range!, listbuilder->list

listbuilder-add-range!

function ↑ Functions

(: listbuilder-add-range! (-> (ListBuilder %a) (Seq %a) void))

Adds every element of a sequence to the end of a builder, in place.

b
The builder.
s
The elements, added in the order the seq yields them.
raises System.InvalidOperationException
When b has already been made into a list.

See also: listbuilder-add!, list->seq

listbuilder-length

function ↑ Functions

(: listbuilder-length (-> (ListBuilder %a) int))

How many elements a builder holds.

b
The builder.
returns
The number of elements added so far. The builder keeps a count, so this does not walk.
raises System.InvalidOperationException
When b has already been made into a list.

See also: list-length

listbuilder->list

function ↑ Functions

(: listbuilder->list (-> (ListBuilder %a) (List %a)))

The list a builder has built.

b
The builder. It cannot be used again afterwards.
returns
A list of the elements added, in order.
raises System.InvalidOperationException
When b has already been made into a list.

Nothing is copied: the cells the builder linked become the list. That is why the builder is finished after it, and every later operation on it, this one included, raises.

See also: listbuilder-empty

over-list

function ↑ Functions

(: over-list (-> (List %a) (ListTails %a)))
(over-list xs)

Returns the successive tails of a list for iteration.

xs
The list.
returns
A sequence yielding xs, its tail, its tail's tail, and so on. The empty list is not yielded.
{listing t (:for t (over-list (list 1 2 3)))}   ; ((1 2 3) (2 3) (3))

(loop (:for tail (over-list xs))
      (:when (> (list-length tail) 1))
      (:acc pairs (listing (Tuple (list-head tail) (list-head (list-tail tail))))))

For a walk that has to look at the rest of the list, not only the element it is on. Each tail is the cell of xs itself, not a copy.

See also: ListTails, list-tail

vec-empty

function ↑ Functions

(: vec-empty (-> (Vec %a)))

An empty vec.

returns
A vec with no elements.

The constructor. The predicate is vec-empty?.

See also: vec-empty?, vecbuilder-empty

vec-empty?

function ↑ Functions

(: vec-empty? (-> (Vec %a) bool))

Whether a vec has no elements.

v
The vec.
returns
#t when its length is 0.

O(1): a vec stores its count, and this reads it.

See also: vec-empty, vec-length

vec-length

function ↑ Functions

(: vec-length (-> (Vec %a) int))

How many elements a vec has.

v
The vec.
returns
Its number of elements.

O(1): a vec stores its count.

See also: vec-empty?

vec-ref

function ↑ Functions

(: vec-ref (-> (Vec %a) int %a))

The element of a vec at an index.

v
The vec.
i
Zero-based index (0 <= i < length).
returns
The element at i.
raises System.IndexOutOfRangeException
When i is negative or not less than the length.

A descent of the tree from the root, unless i is in the last few elements, which are kept in an array of their own. To visit every element, a (:for x v) loop, in-vec or vec-for-each walks the leaf arrays instead and costs less per element.

See also: vec-set, vec-length

vec-contains

function ↑ Functions

(: vec-contains (-> (Vec %a) %a bool))

Whether a vec holds an element.

v
The vec.
x
The element to look for.
returns
#t when some element of v equals x.

A walk from the front that stops at the first match. Elements are compared with .NET’s default equality for the type (EqualityComparer<T>.Default), not through Bjolang’s Eq.

See also: vec-iter

vec-add

function ↑ Functions

(: vec-add (-> (Vec %a) %a (Vec %a)))

Returns a vec with one element added at the end.

v
The persistent vector (unmodified).
x
The element to add.
returns
A new vec, one longer, with x last.

The persistent counterpart of vecbuilder-add!, and what the Addable implementation for Vec calls. To add many elements, a VecBuilder or the vecing collector avoids making a vec per element.

See also: vecbuilder-add!, vec-insert, vec-merge

vec-set

function ↑ Functions

(: vec-set (-> (Vec %a) int %a (Vec %a)))

Returns a vec with the element at an index replaced.

v
The persistent vector (unmodified).
i
Zero-based index (0 <= i < length).
x
The new element.
returns
A new vec with x at i.
raises System.IndexOutOfRangeException
When i is negative or not less than the length.

See also: vec-ref, vecbuilder-set!

vec-insert

function ↑ Functions

(: vec-insert (-> (Vec %a) int %a (Vec %a)))

Returns a vec with an element inserted at an index.

v
The persistent vector (unmodified).
i
Zero-based index at which to insert (0 <= i <= length). If i == length, behaves like vec-add.
x
The element to insert.
returns
A new vec, one longer, with x at i and subsequent elements shifted right.
raises System.IndexOutOfRangeException
When i is negative or greater than the length.

An insertion leaves the tree relaxed, so many of them can make it deeper than a vec built from the front; vec-compact rebuilds it.

See also: vec-add, vec-remove-at, vec-compact

vec-remove-at

function ↑ Functions

(: vec-remove-at (-> (Vec %a) int (Vec %a)))

Returns a vec with the element at an index removed.

v
The persistent vector (unmodified).
i
Zero-based index (0 <= i < length).
returns
A new vec with the element at i removed.
raises System.IndexOutOfRangeException
When i is negative or not less than the length.

See also: vec-insert, vec-pop, vec-pop-first

vec-pop

function ↑ Functions

(: vec-pop (-> (Vec %a) (Vec %a)))

A vec without its last element.

v
The vec, which is left as it was. Not empty.
returns
A new vec, one shorter.
raises System.InvalidOperationException
When v is empty.

See also: vec-pop-first, vec-remove-at, vec-slice

vec-pop-first

function ↑ Functions

(: vec-pop-first (-> (Vec %a) (Vec %a)))

A vec without its first element.

v
The vec, which is left as it was. Not empty.
returns
A new vec, one shorter.
raises System.InvalidOperationException
When v is empty.

(vec-slice v 1 (- (vec-length v) 1)).

See also: vec-pop, vec-slice

vec-slice

function ↑ Functions

(: vec-slice (-> (Vec %a) int int (Vec %a)))

The part of a vec from an index, for a count of elements.

v
The vec, which is left as it was.
start
The first index taken, from 0.
count
How many elements. start plus count is at most the length.
returns
A new vec of count elements, v's from start on.
raises System.ArgumentOutOfRangeException
When start or count is negative, or start plus count is more than the length.
(vec-slice [10 20 30 40] 1 2)   ; [20 30]

A count, not an end index. A count of 0 returns the empty vec, and the whole of v returns v itself. To loop over part of a vec without creating a new one, use in-vec.

See also: vec-split, in-vec, subarray->vec

vec-split

function ↑ Functions

(: vec-split (-> (Vec %a) int (Tuple (Vec %a) (Vec %a))))

Splits a vec into two parts at an index.

v
The persistent vector (unmodified).
i
Split index, from 0 to length inclusive.
returns
A tuple of the first i elements and the rest.
raises System.IndexOutOfRangeException
When i is negative or greater than the length.
(def (front back) (vec-split [1 2 3 4 5] 2))   ; [1 2] and [3 4 5]

See also: vec-slice, vec-merge

vec-merge

function ↑ Functions

(: vec-merge (-> (Vec %a) (Vec %a) (Vec %a)))

Concatenates two vecs into a single vec.

a
The first part (unmodified).
b
The second part (unmodified).
returns
A new vec with a's elements followed by b's.

An RRB concatenation, which joins the two trees rather than copying every element. When either vector is empty it returns the other. The result may be relaxed; vec-compact rebuilds it dense.

See also: vec-add, vec-split, vec-compact

vec-compact

function ↑ Functions

(: vec-compact (-> (Vec %a) (Vec %a)))

Returns a vec with the same elements in a compact, dense tree.

v
The persistent vector (unmodified).
returns
A vec equal to v, rebuilt from the front.

O(n): every element is added to a new builder. Inserting and merging can leave relaxed nodes that make the tree deeper than it needs to be; this is for when that has made access slower. A vec small enough to have no tree is returned unchanged.

See also: vec-insert, vec-merge

vec-map

function ↑ Functions

(: vec-map (-> (-?-> %a %b) (Vec %a) (Vec %b)))
(vec-map f v)

Returns a new vec with a function applied to each element.

f
Applied to each element, front to back.
v
The persistent vector (unmodified).
returns
A new vec of the same length.

The synchronous variant traverses the tree and builds a vec of the same shape. When f is suspending, elements are collected using vecing.

See also: vec-filter, vec-for-each, vec-fold

vec-filter

function ↑ Functions

(: vec-filter (-> (-?-> %a bool) (Vec %a) (Vec %a)))
(vec-filter keep? v)

Returns a new vec keeping only elements that satisfy a predicate.

keep?
Predicate evaluated on each element, front to back.
v
The persistent vector (unmodified).
returns
A new vec of the elements where keep? returned #t, in order.

See also: vec-map, vec-iter

vec-fold

function ↑ Functions

(: vec-fold (-> (-?-> %a %b %b) %b (Vec %a) %b))
(vec-fold f init v)

Reduces a vec’s elements from left to right, starting from an initial value.

f
Accumulator function: (f elem acc).
init
The initial value before the first element.
v
The vec.
returns
The final accumulated value, or init when v is empty.
(vec-fold + 0 [1 2 3])                 ; 6
(vec-fold cons '() [1 2 3])            ; (3 2 1)

See also: vec-reduce, vec-for-each

vec-reduce

function ↑ Functions

(: vec-reduce (-> (-?-> %a %a %a) (Vec %a) %a))
(vec-reduce f v)

Combines a vec’s elements from the front, starting from the first.

f
Called with an element and the value so far: (f elem acc).
v
The vec. Not empty.
returns
The first element combined with each of the others in turn.

f is first called with the second element and the first. An empty vec raises System.InvalidOperationException.

See also: vec-fold

vec-for-each

function ↑ Functions

(: vec-for-each (-> (-?-> %a Unit) (Vec %a) Unit))
(vec-for-each f v)

Calls a function on each element of a vec, for its effect.

f
Called with each element, front to back.
v
The vec.

See also: vec-for-each/range, vec-iter, vec-map

vec-for-each/range

function ↑ Functions

(: vec-for-each/range (-> (-?-> %a Unit) (Vec %a) int int Unit))
(vec-for-each/range f v index count)

Calls a function on a run of a vec’s elements, for its effect.

f
Called with each element of the run, front to back.
v
The vec.
index
The first index visited, from 0.
count
How many elements, 0 or more. index plus count is at most the length.

The run is checked before f is first called, and one that is not in v raises System.ArgumentOutOfRangeException.

See also: vec-for-each, in-vec

vec-iter

function ↑ Functions

(: vec-iter (-> (-?-> %a bool) (Vec %a) bool))
(vec-iter f v)

Calls a function on each element of a vec until it returns #f.

f
Called with each element, front to back. Returning #f stops traversal.
v
The vec.
returns
#t when f returned #t for every element (or if v is empty); #f when stopped early.
(vec-iter (fun (x) (< x 10)) [1 2 30 4])   ; #f, and 4 is never looked at

See also: vec-for-each, vec-contains

vec->list

function ↑ Functions

(: vec->list (-> (Vec %a) (List %a)))
(vec->list v)

The elements of a vec, as a list.

v
The vec.
returns
A list of v's elements, in order.

Fills a list builder with vec-for-each, which walks the leaf arrays.

See also: list->vec, vec->seq

vec->seq

function ↑ Functions

(: vec->seq (-> (Vec %a) (Seq %a)))

The elements of a vec, as a lazy sequence.

v
The vec.
returns
A sequence of v's elements, in order.

Nothing is read until the sequence is walked, and it may be walked more than once, since the vec does not change. Each element is read by index.

See also: ->vec, vec->list

reader->vec

function ↑ Functions

(: reader->vec (-> Bjolang.Runtime.BjoInputPort (Vec string)))

Every remaining line of a .NET text reader, as a vec.

r
The reader. It is read to the end and not closed.
returns
The lines, without their line terminators.

Lines as TextReader.ReadLine splits them, each converted to a Bjolang string and added to a builder. The drains in (std ports) are the usual way to read a port into a vec.

See also: vecbuilder-empty

vecbuilder-empty

function ↑ Functions

(: vecbuilder-empty (-> (VecBuilder %a)))

A new, empty vec builder.

returns
A builder to add to in place and freeze with vecbuilder->vec.
(def b (vecbuilder-empty))
(vecbuilder-add! b 1)
(vecbuilder-add! b 2)
(vecbuilder->vec b)   ; [1 2]

The way to make a vec of many elements without a new vec per element. The vecing collector is one of these under a loop.

See also: vecbuilder-add!, vecbuilder->vec, vec->vecbuilder, Vecing

vecbuilder-empty/small

function ↑ Functions

(: vecbuilder-empty/small (-> (VecBuilder %a)))

A new, empty vec builder for a vec that is likely small.

returns
A builder to add to in place and freeze with vecbuilder->vec.

The same as vecbuilder-empty, except for how it allocates. vecbuilder-empty gives the builder room for 32 elements at the first add. This one gives it room for 4, and doubles the room up to 32 as elements are added. A vec of 4, 8, 16 or 32 elements then takes the builder’s array with no copy.

See also: vecbuilder-empty, VecingSmall

vec->vecbuilder

function ↑ Functions

(: vec->vecbuilder (-> (Vec %a) (VecBuilder %a)))

A builder holding a vec’s elements, to go on adding to.

v
The vec. Changing the builder does not change it.
returns
A builder starting with v's elements.

The builder shares v’s tree and copies a part before it writes to it.

See also: vecbuilder-empty, vecbuilder->vec

vecbuilder-add!

function ↑ Functions

(: vecbuilder-add! (-> (VecBuilder %a) %a void))

Adds an element to the end of a vec builder, in place.

b
The builder.
x
The element to add.

See also: vecbuilder-set!, vec-add, vecbuilder->vec

vecbuilder-set!

function ↑ Functions

(: vecbuilder-set! (-> (VecBuilder %a) int %a void))

Replaces the element at an index in a vec builder, in place.

b
The builder.
i
From 0. Less than the builder's length.
x
The new element.
raises System.IndexOutOfRangeException
When i is negative or not less than the length.

See also: vecbuilder-ref, vec-set

vecbuilder-ref

function ↑ Functions

(: vecbuilder-ref (-> (VecBuilder %a) int %a))

The element at an index in a vec builder.

b
The builder.
i
From 0. Less than the builder's length.
returns
The element at i.

An index out of range raises System.IndexOutOfRangeException, as vec-ref does.

See also: vecbuilder-set!, vecbuilder-length, vec-ref

vecbuilder-length

function ↑ Functions

(: vecbuilder-length (-> (VecBuilder %a) int))

How many elements a vec builder holds.

b
The builder.
returns
Its number of elements.

See also: vecbuilder-ref

vecbuilder->vec

function ↑ Functions

(: vecbuilder->vec (-> (VecBuilder %a) (Vec %a)))

The vec a builder holds.

b
The builder. It may be added to afterwards.
returns
A vec of the builder's elements.

The builder stays usable: what is added or set in it afterwards does not change the previously returned vec.

See also: vecbuilder-empty, vec->vecbuilder

transientvec-empty

function ↑ Functions

(: transientvec-empty (-> (TransientVec %a)))

An empty transient.

returns
A new transient holding nothing.

See also: vec->transientvec

vec->transientvec

function ↑ Functions

(: vec->transientvec (-> (Vec %a) (TransientVec %a)))

A transient holding what a vec holds. O(1).

v
The vec, which no change to the transient affects.
returns
A new transient.

See also: transientvec->vec

transientvec->vec

function ↑ Functions

(: transientvec->vec (-> (TransientVec %a) (Vec %a)))

A vec of what a transient holds. O(1).

t
The transient, which may go on being used.
returns
A new vec, which no later change to t affects.

See also: vec->transientvec

transientvec-length

function ↑ Functions

(: transientvec-length (-> (TransientVec %a) int))

How many elements a transient holds. O(1).

t
The transient.
returns
The number of elements.

transientvec-empty?

function ↑ Functions

(: transientvec-empty? (-> (TransientVec %a) bool))

Whether a transient holds nothing.

t
The transient.
returns
#t when it is empty.

transientvec-ref

function ↑ Functions

(: transientvec-ref (-> (TransientVec %a) int %a))

The element at an index.

t
The transient.
i
The index, from 0.
returns
The element.
raises System.IndexOutOfRangeException
When i is negative or not less than the length.

See also: transientvec-set!

transientvec-set!

function ↑ Functions

(: transientvec-set! (-> (TransientVec %a) int %a void))

Replaces the element at an index, in place.

t
The transient.
i
The index, from 0.
x
The new element.
raises System.IndexOutOfRangeException
When i is negative or not less than the length.

See also: transientvec-ref

transientvec-add!

function ↑ Functions

(: transientvec-add! (-> (TransientVec %a) %a void))

Adds an element at the end, in place.

t
The transient.
x
The element.

See also: transientvec-add-all!, transientvec-add-first!, transientvec-pop!

transientvec-add-all!

function ↑ Functions

(: transientvec-add-all! (-> (TransientVec %a) (Seq %a) void))

Adds the elements of a sequence at the end, in order, in place.

t
The transient.
xs
The elements.

See also: transientvec-add!

transientvec-add-first!

function ↑ Functions

(: transientvec-add-first! (-> (TransientVec %a) %a void))

Adds an element before the first, in place.

t
The transient.
x
The element.

See also: transientvec-pop-first!, transientvec-add!

transientvec-pop!

function ↑ Functions

(: transientvec-pop! (-> (TransientVec %a) %a))

Removes the last element, in place, and answers it.

t
The transient.
returns
The element that was last.
raises System.InvalidOperationException
When the transient is empty.

See also: transientvec-add!, transientvec-pop-first!

transientvec-pop-first!

function ↑ Functions

(: transientvec-pop-first! (-> (TransientVec %a) %a))

Removes the first element, in place, and answers it.

t
The transient.
returns
The element that was first.
raises System.InvalidOperationException
When the transient is empty.
;; A queue: add at the end, take from the front.
(def q (transientvec-empty))
(transientvec-add! q "a")
(transientvec-add! q "b")
(transientvec-pop-first! q)    ; "a"

See also: transientvec-add-first!, transientvec-pop!

vec-cursor

function ↑ Functions

(: vec-cursor (-> (Vec %a) (VecCursor %a)))

A cursor on the first element of a vec, for walking it front to back.

v
The vec.
returns
A cursor on the first element, or a finished cursor for an empty vec.

What Vec’s Iterable implementation walks with. The cursor is a value that walks the vec’s leaf arrays: an array read per element, a lookup per leaf of 32 elements, and nothing allocated. A vec of up to 32 elements is one array.

vec-cursor-done? and vec-cursor-current only read a cursor, and vec-cursor-next answers the cursor one element on.

See also: vec-cursor-done?, vec-cursor-current, vec-cursor-next, vec-cursor-slice

vec-cursor-slice

function ↑ Functions

(: vec-cursor-slice (-> (Vec %a) int int (VecCursor %a)))

A cursor for walking a run of a vec’s elements front to back.

v
The vec.
from
The first index walked, from 0.
count
How many elements. from plus count is at most the length.
returns
A cursor on the first element of the run, or a finished cursor for an empty run.
raises System.ArgumentOutOfRangeException
When the run is not in v.

What VecSlice’s Iterable implementation walks with, and so what in-vec walks with. The cursor is the one vec-cursor makes, so it is read and moved on with the same functions.

See also: vec-cursor, in-vec

vec-cursor-done?

function ↑ Functions

(: vec-cursor-done? (-> (VecCursor %a) bool))

Whether a vec cursor has walked past the last element.

c
The cursor.
returns
#t when the walk is over; #f when the cursor is on an element.

See also: vec-cursor, vec-cursor-current, vec-cursor-next

vec-cursor-current

function ↑ Functions

(: vec-cursor-current (-> (VecCursor %a) %a))

The element a vec cursor is on.

c
The cursor, when vec-cursor-done? says #f.
returns
The element.

See also: vec-cursor, vec-cursor-done?, vec-cursor-next

vec-cursor-next

function ↑ Functions

(: vec-cursor-next (-> (VecCursor %a) (VecCursor %a)))

The cursor one element further on.

c
The cursor, when vec-cursor-done? says #f.
returns
A cursor on the next element, or a finished cursor after the last.

The cursor given does not change, so it still reads the element it was on.

See also: vec-cursor, vec-cursor-done?, vec-cursor-current

vec-back-cursor

function ↑ Functions

(: vec-back-cursor (-> (Vec %a) int int (VecBackCursor %a)))

A cursor for walking a run of a vec’s elements backwards.

v
The vec.
last
The first index walked, the highest of the run. -1 with a count of 0 is the empty run.
count
How many elements, going down from last. last minus count is at least -1.
returns
A cursor on the first element of the run, or a finished cursor for an empty run.
raises System.ArgumentOutOfRangeException
When the run is not in v.

What ReverseVecSlice’s Iterable implementation calls, and so what in-reverse-vec walks with; it is exported because that implementation’s body names it.

See also: vec-back-cursor-done?, vec-back-cursor-current, vec-back-cursor-next, in-reverse-vec

vec-back-cursor-done?

function ↑ Functions

(: vec-back-cursor-done? (-> (VecBackCursor %a) bool))

Whether a backward vec cursor has walked past the lowest element of its run.

c
The cursor.
returns
#t when the run is over; #f when the cursor is on an element.

See also: vec-back-cursor, vec-back-cursor-current, vec-back-cursor-next

vec-back-cursor-current

function ↑ Functions

(: vec-back-cursor-current (-> (VecBackCursor %a) %a))

The element a backward vec cursor is on.

c
The cursor, when vec-back-cursor-done? says #f.
returns
The element.

See also: vec-back-cursor, vec-back-cursor-done?, vec-back-cursor-next

vec-back-cursor-next

function ↑ Functions

(: vec-back-cursor-next (-> (VecBackCursor %a) (VecBackCursor %a)))

The backward cursor one element further on, which is one index lower.

c
The cursor, when vec-back-cursor-done? says #f.
returns
A cursor on the next element, or a finished cursor after the last.

See also: vec-back-cursor, vec-back-cursor-done?, vec-back-cursor-current

in-vec

function ↑ Functions

(: in-vec (-> (Vec %a) (#:from int) (#:to int) (VecSlice %a)))
(in-vec v #:from 0 #:to (vec-length v))

Part of a vec, to walk front to back in a loop.

v
The vec.
#:from
The first index walked, included.
#:to
The index the walk stops before, not included.
returns
A slice that a (:for ...) clause walks.
(loop (:for x (in-vec v #:from 1 #:to 4))   ; elements 1, 2 and 3
      (:do (displayln x)))

Makes no new vec: the slice is a small value holding v and the bounds, and the walk goes through the leaf arrays rather than calling vec-ref per index, so part of a vec costs what the whole costs per element.

The bounds are checked once, when the slice is made. When #:from is negative, #:to is past the length or #:from is past #:to, it panics with a message naming the bounds.

See also: in-reverse-vec, VecSlice, vec-slice

in-reverse-vec

function ↑ Functions

(: in-reverse-vec (-> (Vec %a) (#:from int) (#:to int) (ReverseVecSlice %a)))
(in-reverse-vec v #:from 0 #:to (vec-length v))

Part of a vec, to walk back to front in a loop.

v
The vec.
#:from
The lowest index walked, included; the last one visited.
#:to
The index above the first one visited, not included.
returns
A slice that a (:for ...) clause walks.
(loop (:for x (in-reverse-vec v #:from 2 #:to 5))   ; elements 4, 3 and 2
      (:do (displayln x)))

The same slice in-vec takes with the same bounds, walked the other way. The bounds are checked as in-vec checks them.

See also: in-vec, ReverseVecSlice

make-array

function ↑ Functions

(: make-array (-> int %a (Array %a)))

A new .NET array of a length.

n
The length.
returns
An array of n elements, each .NET's default for the type: zero for a number.

See also: array-ref, array-set!, array-resize

array-ref

function ↑ Functions

(: array-ref (-> (Array %a) int %a))

The element of an array at an index.

a
The array.
i
From 0. Less than the length.
returns
The element at i.

a[i], with .NET’s bounds check.

See also: array-set!, array-length, vec-ref

array-set!

function ↑ Functions

(: array-set! (-> (Array %a) int %a void))

Replaces the element of an array at an index, in place.

a
The array, which is changed.
i
From 0. Less than the length.
x
The new element.

a[i] = x, with .NET’s bounds check.

See also: array-ref

array-length

function ↑ Functions

(: array-length (-> (Array %a) int))

How many elements an array has.

a
The array.
returns
Its length.

See also: make-array

array-resize

function ↑ Functions

(: array-resize (-> (Array %a) int (Array %a)))

A new array of another length, holding as much of an array as fits.

a
The array, which is left as it was.
n
The new length. Larger grows, smaller shrinks.
returns
A new array of n elements: a's first ones, then .NET's default for the type.

What a growable array is written over: make-array, and this when it fills up. It always copies, so the old array is not the new one.

See also: make-array

array->vec

function ↑ Functions

(: array->vec (-> (Array %a) (Vec %a)))

A vec of an array’s elements.

a
The array, which is copied: changing it afterwards does not change the vec.
returns
A vec of a's elements, in order.

The elements go straight into the tree’s leaves in one walk, with no add per element, so an array is the cheapest thing to build a vec out of. It suits making a great many small vecs, where a builder is sized for large ones.

See also: subarray->vec, vecbuilder-empty

subarray->vec

function ↑ Functions

(: subarray->vec (-> (Array %a) int int (Vec %a)))

A vec of a run of an array’s elements.

a
The array, which is copied.
start
The first index taken, from 0.
count
How many elements. start plus count is at most the length.
returns
A vec of count elements, a's from start on.

Start and count, as vec-slice takes them.

See also: array->vec, vec-slice

in-array

function ↑ Functions

(: in-array (-> (Array %a) (#:from int) (#:to int) (ArraySlice %a)))
(in-array arr #:from 0 #:to (array-length arr))

Part of an array, to walk front to back in a loop.

arr
The array.
#:from
The first index walked, included.
#:to
The index the walk stops before, not included.
returns
A slice that a (:for ...) clause walks.
(loop (:for x (in-array a #:from 2))   ; from element 2 to the end
      (:do (displayln x)))

The slice is a small value holding the array and the bounds, and the walk is an int index and array-ref. The bounds are checked once, when the slice is made. When #:from is negative, #:to is past the length or #:from is past #:to, it panics with a message naming the bounds.

See also: in-reverse-array, ArraySlice, in-vec

in-reverse-array

function ↑ Functions

(: in-reverse-array (-> (Array %a) (#:from int) (#:to int) (ReverseArraySlice %a)))
(in-reverse-array arr #:from 0 #:to (array-length arr))

Part of an array, to walk back to front in a loop.

arr
The array.
#:from
The lowest index walked, included; the last one visited.
#:to
The index above the first one visited, not included.
returns
A slice that a (:for ...) clause walks.
(loop (:for x (in-reverse-array a #:from 2 #:to 5))   ; elements 4, 3 and 2
      (:do (displayln x)))

The same slice in-array takes with the same bounds, walked the other way. The bounds are checked as in-array checks them.

See also: in-array, ReverseArraySlice

vec-take

function ↑ Functions

(: vec-take (-> (Vec %a) int (Vec %a)))
(vec-take v n)

The first n elements of a vec.

v
The vec, which is left as it was.
n
How many elements, 0 or more.
returns
A vec of the first n elements; all of v when it has fewer.
(vec-take [1 2 3 4] 2)    ; [1 2]
(vec-take [1 2] 10)       ; [1 2]

vec-slice from 0. A negative n is refused with a panic.

See also: vec-drop, vec-slice

vec-drop

function ↑ Functions

(: vec-drop (-> (Vec %a) int (Vec %a)))
(vec-drop v n)

A vec without its first n elements.

v
The vec, which is left as it was.
n
How many elements, 0 or more.
returns
A vec of the elements after the first n; the empty vec when v has n or fewer.
(vec-drop [1 2 3 4] 1)    ; [2 3 4]

vec-slice from n. A negative n is refused with a panic.

See also: vec-take, vec-slice

vec-reverse

function ↑ Functions

(: vec-reverse (-> (Vec %a) (Vec %a)))
(vec-reverse v)

A vec in the reverse order.

v
The vec, which is left as it was.
returns
A new vec of the same elements, last first.
(vec-reverse [1 2 3])     ; [3 2 1]

Walks v backwards once. To only walk it backwards, in-reverse-vec makes no new vec.

See also: in-reverse-vec

vec->array

function ↑ Functions

(: vec->array (-> (Vec %a) (Array %a)))

The elements of a vec in a new array.

v
The vec, which is left as it was.
returns
An array of the elements, in order, which v does not share.
(array-length (vec->array [1 2 3]))   ; 3

See also: array->vec, subarray->vec

map-empty

function ↑ Functions

(: map-empty (-> (Map %k %v)))
(map-empty)

An empty map.

returns
A map with no entries, comparing keys with the key type's Eq.

See also: map-clear, ->map, list->map

map-clear

function ↑ Functions

(: map-clear (-> (Map %k %v) (Map %k %v)))

An empty map that compares keys as another does.

m
The map whose key comparison to keep.
returns
An empty map.

See also: map-empty, map-remove-all

map-ref

function ↑ Functions

(: map-ref (-> (Map %k %v) %k %v))

The value under a key, which must be there.

m
The map.
k
The key.
returns
The value under k.
raises System.Collections.Generic.KeyNotFoundException
When k is not in the map.

See also: map-ref-or, map-try-ref, ref

map-ref-or

function ↑ Functions

(: map-ref-or (-> (Map %k %v) %k %v %v))

The value under a key, or a default when it is not there.

m
The map.
k
The key.
default
The fallback value returned if k is absent.
returns
The value under k, or default.

See also: map-ref, map-try-ref

map-try-ref

function ↑ Functions

(: map-try-ref (-> (Map %k %v) %k (out %v) (Option %v)))

The value under a key, if it is there.

m
The map.
k
The key.
returns
(Some v) for the value under k, or None.
(map-try-ref #map(("a" 1)) "a")   ; (Some 1)
(map-try-ref #map(("a" 1)) "b")   ; None

See also: map-ref, map-ref-or, try-ref

map-contains?

function ↑ Functions

(: map-contains? (-> (Map %k %v) %k bool))

Whether a map has a key.

m
The map.
k
The key.
returns
#t when k is in the map.

See also: map-has-key?, map-try-ref

map-has-key?

function ↑ Functions

(: map-has-key? (-> (Map %k %v) %k bool))
(map-has-key? m key)

Whether a map has a key.

m
The map.
key
The key.
returns
#t when key is in the map.

The same as map-contains?.

See also: map-contains?

map-length

function ↑ Functions

(: map-length (-> (Map %k %v) int))

How many entries a map has.

m
The map.
returns
The number of keys.

See also: map-empty?, length

map-empty?

function ↑ Functions

(: map-empty? (-> (Map %k %v) bool))

Whether a map has no entries.

m
The map.
returns
#t when the map has no keys.

See also: map-length, empty?

map-keys

function ↑ Functions

(: map-keys (-> (Map %k %v) (Seq %k)))

The keys of a map.

m
The map.
returns
A sequence of the keys, in the trie's order.

See also: map-values, map->seq

map-values

function ↑ Functions

(: map-values (-> (Map %k %v) (Seq %v)))

The values of a map.

m
The map.
returns
A sequence of the values, in the trie's order.

See also: map-keys, map->seq

map-set

function ↑ Functions

(: map-set (-> (Map %k %v) %k %v (Map %k %v)))

A map with a key set to a value, replacing or adding it.

m
The persistent map (unmodified).
k
The key.
v
Its value.
returns
A map with k mapped to v.

When k already holds a value equal to v, by the value type’s .NET Equals, it returns m itself unchanged.

See also: map-add, map-set-all, ref-set

map-add

function ↑ Functions

(: map-add (-> (Map %k %v) %k %v (Map %k %v)))

A map with a key that was not there added.

m
The map, which is left as it was. Without k.
k
The key.
v
Its value.
returns
A map with k mapped to v.
raises System.ArgumentException
When k is already in the map.

map-set without the replacement. The add of the Addable trait replaces instead, as map-set does.

See also: map-set, add

map-set-all

function ↑ Functions

(: map-set-all (-> (Map %k %v) (Seq (Tuple %k %v)) (Map %k %v)))

A map with every entry of a sequence set.

m
The map, which is left as it was.
kvs
The (key value) pairs to set, in order: a later pair wins over an earlier one with the same key.
returns
The map with every pair set.

Through a transient, so the trie is copied once rather than once per entry.

See also: map-set, map-merge, transientmap-set-all!

map-remove

function ↑ Functions

(: map-remove (-> (Map %k %v) %k (Map %k %v)))

A map without a key.

m
The map, which is left as it was.
k
The key to remove.
returns
The map without k. When k is not there, m itself.

See also: map-remove-all, map-filter

map-remove-all

function ↑ Functions

(: map-remove-all (-> (Map %k %v) (Seq %k) (Map %k %v)))

A map without every key of a sequence.

m
The map, which is left as it was.
ks
The keys to remove. A key that is not there is skipped.
returns
The map without those keys.

Through a transient, so the trie is copied once rather than once per key.

See also: map-remove, transientmap-remove-all!

map-merge

function ↑ Functions

(: map-merge (-> (Map %k %v) (Map %k %v) (Map %k %v)))

One map laid over another: where both have a key, the second’s value wins.

m
The map underneath.
other
The map laid over it.
returns
Every key of either, with other's value where both have one.

The result compares keys as m does. The merge is cheap where the two maps share a history: a subtree that both have untouched is taken whole rather than walked.

See also: map-merge-with, map-set-all

map-merge-with

function ↑ Functions

(: map-merge-with (-> (-> %k %v %v %v) (Map %k %v) (Map %k %v) (Map %k %v)))

Two maps merged, with a function deciding the keys both have.

f
Merger function (f key left right) returning the resolved value.
m
The left map.
other
The right map.
returns
A map containing all keys from both maps, with conflicts resolved by f.
(map-merge-with (fun (k a b) (+ a b))
                #map(("x" 1) ("y" 2))
                #map(("y" 10)))   ; x 1, y 12

The result compares keys as m does.

See also: map-merge

map-map

function ↑ Functions

(: map-map (-> (-?-> %k %v %w) (Map %k %v) (Map %k %w)))
(map-map f m)

A map with every value replaced by a function of its key and value.

f
Function (f key value) returning the new value.
m
The map.
returns
A map containing the same keys with updated values.

The key is what the result is filed under, so f cannot move it.

See also: map-map-values, map-filter

map-map-values

function ↑ Functions

(: map-map-values (-> (-?-> %v %w) (Map %k %v) (Map %k %w)))
(map-map-values f m)

A map with every value replaced by a function of the value.

f
Function (f value) returning the new value.
m
The map.
returns
A map containing the same keys with updated values.

See also: map-map

map-filter

function ↑ Functions

(: map-filter (-> (-?-> %k %v bool) (Map %k %v) (Map %k %v)))
(map-filter keep? m)

The entries of a map that a predicate keeps.

keep?
Called as (keep? key value); #t keeps the entry.
m
The map.
returns
A map of the entries kept, filed under the same comparison.

See also: map-remove-all, transientmap-filter!, map-find

map-fold

function ↑ Functions

(: map-fold (-> (-?-> %k %v %s %s) %s (Map %k %v) %s))
(map-fold f init m)

Combines every entry of a map into one value.

f
Accumulator function (f key value acc) returning the next accumulator.
init
The acc before the first entry.
m
The map.
returns
The final accumulator value, or init for an empty map.
(map-fold (fun (k v acc) (+ acc v)) 0 m)   ; the sum of the values

The entries come in the trie’s order.

See also: map-for-each, fold

map-for-each

function ↑ Functions

(: map-for-each (-> (-?-> %k %v void) (Map %k %v) void))
(map-for-each f m)

Calls a function on every entry of a map, for its effect.

f
Called as (f key value).
m
The map.

See also: map-iter, map-fold

map-iter

function ↑ Functions

(: map-iter (-> (-?-> %k %v bool) (Map %k %v) bool))
(map-iter f m)

Traverses a map until a function returns #f.

f
Called as (f key value); returning #f stops traversal.
m
The map.
returns
#t if the traversal completed without f returning #f; #f otherwise.

See also: map-for-each, map-any?, map-find

map-any?

function ↑ Functions

(: map-any? (-> (-> %k %v bool) (Map %k %v) bool))

Whether a predicate holds of some entry of a map.

pred
Called as (pred key value).
m
The map.
returns
#t at the first entry pred holds of; #f when there is none.

See also: map-find, map-iter

map-find

function ↑ Functions

(: map-find (-> (-> %k %v bool) (Map %k %v) (Option (Tuple %k %v))))
(map-find pred m)

The first entry of a map that a predicate holds of.

pred
Called as (pred key value).
m
The map.
returns
(Some (Tuple key value)) for the entry, or None.

First in the trie’s order, which is no order to rely on: when several entries match, which one is found is unspecified.

See also: map-try-find, map-any?, map-filter

map-try-find

function ↑ Functions

(: map-try-find (-> (-> %k %v bool) (Map %k %v) (out %k) (out %v) (Option (Tuple %k %v))))

The first entry of a map that a predicate holds of.

pred
Called as (pred key value).
m
The map.
returns
(Some (Tuple key value)) for the entry, or None.

The same as map-find.

See also: map-find

map-cursor

function ↑ Functions

(: map-cursor (-> (Map %k %v) (MapCursor %k %v)))

A cursor on the first entry of a map.

m
The map to walk.
returns
A cursor on the first entry, or a done cursor if the map is empty.

See also: map-cursor-done?, map-cursor-current, map-cursor-next, MapCursor

map-cursor-done?

function ↑ Functions

(: map-cursor-done? (-> (MapCursor %k %v) bool))

Tests whether a cursor is past the last entry.

c
The cursor. It does not change.
returns
#t when the walk has no more entries; #f if the cursor is on an entry.
(let go ((c (map-cursor m)))
  (unless (map-cursor-done? c)
    (displayln (displayed (map-cursor-current c)))
    (go (map-cursor-next c))))

See also: map-cursor, map-cursor-current, map-cursor-next

map-cursor-current

function ↑ Functions

(: map-cursor-current (-> (MapCursor %k %v) (Tuple %k %v)))

The entry a cursor is on.

c
The cursor, when map-cursor-done? returns #f.
returns
The entry, as (Tuple key value).

See also: map-cursor, map-cursor-done?, map-cursor-next

map-cursor-next

function ↑ Functions

(: map-cursor-next (-> (MapCursor %k %v) (MapCursor %k %v)))

A cursor on the entry after the entry of a cursor.

c
The cursor, when map-cursor-done? returns #f. It does not change.
returns
The cursor one entry on.

See also: map-cursor, map-cursor-done?, map-cursor-current

list->map

function ↑ Functions

(: list->map (-> (List (Tuple %k %v)) (Map %k %v)))
(list->map xs)

A map of the (key value) pairs of a list.

xs
The pairs. A later pair wins over an earlier one with the same key.
returns
The map, comparing keys with the key type's Eq.

What the #map(...) literal expands to.

See also: map->list, vec->map, ->map, Mapping

vec->map

function ↑ Functions

(: vec->map (-> (Vec (Tuple %k %v)) (Map %k %v)))
(vec->map v)

A map of the (key value) pairs of a vec.

v
The pairs. A later pair wins over an earlier one with the same key.
returns
The map, comparing keys with the key type's Eq.

See also: map->vec, list->map, ->map

seq->map

function ↑ Functions

(: seq->map (-> (Seq (Tuple %k %v)) (Map %k %v)))
(seq->map xs)

Deprecated: use ->map. A map of the (key value) pairs of a sequence.

xs
The pairs. A later pair wins over an earlier one with the same key.
returns
The map, comparing keys with the key type's Eq.

->map takes any iterable of pairs, and fuses with a chain under it. A use of seq->map warns, and it goes in a later release.

See also: ->map

map->list

function ↑ Functions

(: map->list (-> (Map %k %v) (List (Tuple %k %v))))
(map->list m)

The entries of a map, as a list of pairs.

m
The map.
returns
A list of (Tuple key value), in the trie's order.

See also: list->map, map->vec, map->seq

map->vec

function ↑ Functions

(: map->vec (-> (Map %k %v) (Vec (Tuple %k %v))))
(map->vec m)

The entries of a map, as a vec of pairs.

m
The map.
returns
A vec of (Tuple key value), in the trie's order.

See also: vec->map, map->list, map->seq

map->seq

function ↑ Functions

(: map->seq (-> (Map %k %v) (Seq (Tuple %k %v))))

The entries of a map, as a sequence of pairs.

m
The map.
returns
A sequence of (Tuple key value), in the trie's order.

See also: ->map, map-keys, map-values

map->str

function ↑ Functions

(: map->str (-> (Map %k %v) string))
(map->str m)

Deprecated: use displayed. A map written out as text.

m
The map.
returns
#map( and ) around the entries, each key and value displayed inside parentheses, separated by spaces.
(displayed (map-set (map-empty) 1 2))   ; #map((1 2))

What displayed gives for a map, so (println m) prints this. A string is displayed without its quotes. written gives text that reads back as a #map(...) literal when the keys and values are written so that they read back.

See also: displayed, written

map-entry->str

function ↑ Functions

(: map-entry->str (-> (Tuple %k %v) string))
(map-entry->str entry)

Deprecated: use displayed on the key and the value. A (key value) pair written out as text.

entry
The pair.
returns
The key displayed and the value displayed, separated by a space.

See also: displayed

mapbuilder-empty

function ↑ Functions

(: mapbuilder-empty (-> (MapBuilder %k %v)))
(mapbuilder-empty)

An empty map builder.

returns
A builder whose map will compare keys with the key type's Eq.

See also: map->mapbuilder, mapbuilder-add!, MapBuilder

map->mapbuilder

function ↑ Functions

(: map->mapbuilder (-> (Map %k %v) (MapBuilder %k %v)))

A map builder that starts with the entries of a map.

m
The map, which is left as it was.
returns
A builder holding m's entries, comparing keys as m does.

A key added afterwards replaces m’s value for it when the map is built. To change an existing map, map->transientmap copies less.

See also: mapbuilder-empty, map->transientmap

mapbuilder-add!

function ↑ Functions

(: mapbuilder-add! (-> (MapBuilder %k %v) %k %v void))

Appends an entry to a map builder.

b
The builder.
k
The key.
v
Its value. A key appended twice keeps the last value.

See also: mapbuilder-add-all!, mapbuilder->map, add!

mapbuilder-add-all!

function ↑ Functions

(: mapbuilder-add-all! (-> (MapBuilder %k %v) (Seq (Tuple %k %v)) void))

Appends every (key value) pair of a sequence to a map builder.

b
The builder.
kvs
The pairs, appended in order.

See also: mapbuilder-add!, add-all!

mapbuilder-length

function ↑ Functions

(: mapbuilder-length (-> (MapBuilder %k %v) int))

How many entries have been appended to a map builder.

b
The builder.
returns
The number of appends, counting a repeated key each time.

Keys appended twice are resolved when the map is built, so this is an upper bound on the size of the map to come, not its size.

See also: mapbuilder->map

mapbuilder->map

function ↑ Functions

(: mapbuilder->map (-> (MapBuilder %k %v) (Map %k %v)))

Builds the map a builder holds.

b
The builder.
returns
The map of the entries appended, the last value winning for a repeated key.

See also: mapbuilder-empty, MapBuilder

transientmap-empty

function ↑ Functions

(: transientmap-empty (-> (TransientMap %k %v)))
(transientmap-empty)

An empty transient map.

returns
A transient comparing keys with the key type's Eq.

See also: map->transientmap, TransientMap

map->transientmap

function ↑ Functions

(: map->transientmap (-> (Map %k %v) (TransientMap %k %v)))

A transient map holding the entries of a map.

m
The map, which is left as it was.
returns
A transient that writes in place, comparing keys as m does.

Nothing is copied up front: the transient copies a node the first time it writes to it.

See also: transientmap->map, transientmap-empty

transientmap->map

function ↑ Functions

(: transientmap->map (-> (TransientMap %k %v) (Map %k %v)))

The map a transient holds, as it stands.

t
The transient, which stays usable.
returns
A persistent map, made in O(1).

The transient disowns the nodes it handed over, so a later write to it copies them rather than modifying the returned map.

See also: map->transientmap

transientmap-set!

function ↑ Functions

(: transientmap-set! (-> (TransientMap %k %v) %k %v void))

Sets a key of a transient map to a value, in place.

t
The transient.
k
The key.
v
Its value, replacing any it had.

See also: transientmap-set-all!, map-set

transientmap-set-all!

function ↑ Functions

(: transientmap-set-all! (-> (TransientMap %k %v) (Seq (Tuple %k %v)) void))

Sets every (key value) pair of a sequence in a transient map, in place.

t
The transient.
kvs
The pairs, set in order: a later pair wins.

See also: transientmap-set!, map-set-all

transientmap-remove!

function ↑ Functions

(: transientmap-remove! (-> (TransientMap %k %v) %k void))

Removes a key from a transient map, in place.

t
The transient.
k
The key. When it is not there, nothing happens.

See also: transientmap-remove-all!, map-remove

transientmap-remove-all!

function ↑ Functions

(: transientmap-remove-all! (-> (TransientMap %k %v) (Seq %k) void))

Removes every key of a sequence from a transient map, in place.

t
The transient.
ks
The keys. One that is not there is skipped.

See also: transientmap-remove!, map-remove-all

transientmap-filter!

function ↑ Functions

(: transientmap-filter! (-> (-> %k %v bool) (TransientMap %k %v) void))

Removes the entries of a transient map that a predicate rejects, in place.

keep?
Called as (keep? key value); #f removes the entry.
t
The transient.

The keys to remove are all found before any is removed, so the predicate sees the transient as it was.

See also: map-filter, transientmap-remove-all!

transientmap-ref

function ↑ Functions

(: transientmap-ref (-> (TransientMap %k %v) %k %v))

The value under a key of a transient map, which must be there.

t
The transient.
k
The key.
returns
The value under k.
raises System.Collections.Generic.KeyNotFoundException
When k is not in the transient.

See also: transientmap-ref-or, transientmap-try-ref, map-ref

transientmap-ref-or

function ↑ Functions

(: transientmap-ref-or (-> (TransientMap %k %v) %k %v %v))

The value under a key of a transient map, or a default.

t
The transient.
k
The key.
default
The fallback value returned if k is absent.
returns
The value under k, or default.

See also: transientmap-ref, transientmap-try-ref

transientmap-try-ref

function ↑ Functions

(: transientmap-try-ref (-> (TransientMap %k %v) %k (out %v) (Option %v)))

The value under a key of a transient map, if it is there.

t
The transient.
k
The key.
returns
(Some v) for the value under k, or None.

See also: transientmap-ref, transientmap-ref-or

transientmap-contains?

function ↑ Functions

(: transientmap-contains? (-> (TransientMap %k %v) %k bool))

Whether a transient map has a key.

t
The transient.
k
The key.
returns
#t when k is there.

See also: transientmap-try-ref, map-contains?

transientmap-length

function ↑ Functions

(: transientmap-length (-> (TransientMap %k %v) int))

How many entries a transient map holds.

t
The transient.
returns
The number of keys, as it stands.

See also: transientmap-empty?, map-length

transientmap-empty?

function ↑ Functions

(: transientmap-empty? (-> (TransientMap %k %v) bool))

Whether a transient map holds no entries.

t
The transient.
returns
#t when it has no keys.

See also: transientmap-length, map-empty?

str

function ↑ Functions

(: str (-> #:rest string string))
(str #:rest parts)

Concatenates any number of strings.

parts ...
The strings, in order.
returns
Their text, one after the other. No parts is the empty string.
(str "n = " (int->string n) "!")

Every part must already be a string: str formats nothing, so a number goes through int->string or displayed first. The result is made in one allocation of the exact size.

In a loop, collect into a builder or a stringing clause instead: appending to a growing string copies it every time, and is quadratic.

See also: string-append, string-join

string-append

function ↑ Functions

(: string-append (-> string string string))
(string-append a b)

Concatenates two strings.

a
The first.
b
The second.
returns
The text of a followed by that of b. When either is empty, the other.

See also: str, string-join

string-length

function ↑ Functions

(: string-length (-> string int))
(string-length s)

The length of a string in bytes of UTF-8.

s
The string.
returns
The number of bytes. O(1).
(string-length "héllo")   ; 6
(string-count "héllo")    ; 5

The storage length, for sizing a buffer. It is not “how long is this text”: for that, string-count counts characters. The two differ for any string with a character outside ASCII in it, which is why neither is called size.

See also: string-count, string-empty?

string-count

function ↑ Functions

(: string-count (-> string int))

The number of characters in a string.

s
The string.
returns
How many characters (Unicode scalar values) s holds.

O(n): the characters are counted, not stored. string-length is the O(1) byte length. length on a string returns this count as well.

See also: string-length, length

string-empty?

function ↑ Functions

(: string-empty? (-> string bool))

Whether a string has no characters.

s
The string.
returns
#t for the empty string.

See also: string-length

string->clr-string

function ↑ Functions

(: string->clr-string (-> string System.String))

The same text as a .NET System.String.

s
The string.
returns
A UTF-16 System.String with the same characters.

A .NET member that takes a System.String directly is converted at the call, so this is needed only for a .NET string inside another type, such as an element of a (Seq System.String) or the argument of a Func.

See also: clr-string->string

string-contains?

function ↑ Functions

(: string-contains? (-> string string bool))
(string-contains? s needle)

Whether a string contains another.

s
The string to search.
needle
The text to look for. An empty one is always found.
returns
#t when needle occurs in s.

Ordinal: bytes are compared as they are, with no culture. For case-insensitive search, fold the case of both first: (string-contains? (string-downcase s) (string-downcase needle)).

See also: string-search, string-starts-with?, string-ends-with?

string-starts-with?

function ↑ Functions

(: string-starts-with? (-> string string bool))
(string-starts-with? s prefix)

Whether a string starts with another.

s
The string.
prefix
What it may start with.
returns
#t when s begins with prefix. Every string starts with the empty one.

Ordinal, as string-contains? is.

See also: string-ends-with?, string-contains?

string-ends-with?

function ↑ Functions

(: string-ends-with? (-> string string bool))
(string-ends-with? s suffix)

Whether a string ends with another.

s
The string.
suffix
What it may end with.
returns
#t when s ends with suffix. Every string ends with the empty one.

Ordinal, as string-contains? is.

See also: string-starts-with?, string-contains?

string-replace

function ↑ Functions

(: string-replace (-> string string string string))
(string-replace s old new)

A string with every occurrence of one text replaced by another.

s
The string.
old
The text to replace. Not empty.
new
What goes in its place. The empty string deletes.
returns
s with each occurrence of old replaced, left to right and not overlapping; s itself when there is none.
raises System.ArgumentException
When old is empty.
(string-replace "a-b-c" "-" "")    ; "abc"
(string-replace "aaa" "aa" "b")    ; "ba"

Ordinal, as string-contains? is.

See also: string-search, string-contains?

function ↑ Functions

(: string-search (-> string string (Option StringCursor)))

Where the first occurrence of a text in a string starts.

s
The string to search.
needle
The text to look for.
returns
(Some cursor) on the start of the first occurrence, or None. An empty needle is found at the start.
(match (string-search line "=")
  ((Some c) (substring line (string-cursor-start line) c))   ; the key
  (None line))

Ordinal. The returned cursor can be passed directly to substring; there is no byte index to get wrong. In a slice, the cursor is a position in the string the slice was taken from.

See also: string-search-backward, string-index, substring, string-contains?

string-search-backward

function ↑ Functions

(: string-search-backward (-> string string (Option StringCursor)))

Where the last occurrence of a text in a string starts.

s
The string to search.
needle
The text to look for.
returns
(Some cursor) on the start of the last occurrence, or None. An empty needle is found at the end.

See also: string-search, substring

string-index

function ↑ Functions

(: string-index (-> (-> char bool) string (Option StringCursor)))
(string-index pred s)

Where the first character satisfying a predicate is.

pred
The test, given each character in turn from the start.
s
The string.
returns
(Some cursor) on the first character pred returns #t for, or None.
(string-index char-whitespace? "key value")   ; (Some cursor) on the space

A cursor rather than a character, so the result goes straight to substring. It stops at the first match.

See also: string-search, substring

string-upcase

function ↑ Functions

(: string-upcase (-> string string))
(string-upcase s)

A string with every character upper-cased.

s
The string.
returns
The upper-cased text; s itself when no character changes.

Invariant culture, character for character: ß upcases to itself rather than to SS, so this is for normalising before a comparison rather than for display.

See also: string-downcase, char-upcase

string-downcase

function ↑ Functions

(: string-downcase (-> string string))
(string-downcase s)

A string with every character lower-cased.

s
The string.
returns
The lower-cased text; s itself when no character changes.

Invariant culture, character for character. Downcase both sides before an ordinal comparison or search to ignore case.

See also: string-upcase, char-downcase, char-foldcase

string-trim

function ↑ Functions

(: string-trim (-> string string))
(string-trim s)

A string without the whitespace at both ends.

s
The string.
returns
s with leading and trailing whitespace removed.

Whitespace is what char-whitespace? says it is. There is no form that trims other characters. The result has bytes of its own, unless nothing was trimmed, when it is s itself.

See also: string-trim-left, string-trim-right, string-trim/slice, char-whitespace?

string-trim-left

function ↑ Functions

(: string-trim-left (-> string string))
(string-trim-left s)

A string without the whitespace at its start.

s
The string.
returns
s with leading whitespace removed.

See also: string-trim, string-trim-right, string-trim-left/slice

string-trim-right

function ↑ Functions

(: string-trim-right (-> string string))
(string-trim-right s)

A string without the whitespace at its end.

s
The string.
returns
s with trailing whitespace removed.

See also: string-trim, string-trim-left, string-trim-right/slice

string-trim/slice

function ↑ Functions

(: string-trim/slice (-> string string))
(string-trim/slice s)

Returns the trimmed string as a zero-copy slice.

s
The string.
returns
s without whitespace at either end, sharing s's bytes.

No copy is made, and the slice keeps all of s’s bytes alive. For a scanner that cuts many short pieces out of one text and lets them go; string-copy a piece before keeping it.

See also: string-trim, string-copy, substring/slice

string-trim-left/slice

function ↑ Functions

(: string-trim-left/slice (-> string string))
(string-trim-left/slice s)

Returns the left-trimmed string as a zero-copy slice.

s
The string.
returns
s without leading whitespace, sharing s's bytes.

See also: string-trim-left, string-trim/slice, string-copy

string-trim-right/slice

function ↑ Functions

(: string-trim-right/slice (-> string string))
(string-trim-right/slice s)

Returns the right-trimmed string as a zero-copy slice.

s
The string.
returns
s without trailing whitespace, sharing s's bytes.

See also: string-trim-right, string-trim/slice, string-copy

string-pad-left

function ↑ Functions

(: string-pad-left (-> string int (#:with char) string))
(string-pad-left s width #:with #\space)

A string padded at the start to a width in characters.

s
The string.
width
The width wanted, in characters.
#:with
The character to pad with.
returns
s with enough copies of the pad before it to make width characters; s's text unchanged when it is already that wide.
(string-pad-left "7" 3 #:with #\0)   ; "007"
(string-pad-left "1234" 3)           ; "1234"

The width is string-count’s count, not string-length’s, and the pad is one character however many bytes it takes. It never truncates.

See also: string-pad-right, string-count

string-pad-right

function ↑ Functions

(: string-pad-right (-> string int (#:with char) string))
(string-pad-right s width #:with #\space)

A string padded at the end to a width in characters.

s
The string.
width
The width wanted, in characters.
#:with
The character to pad with.
returns
s with enough copies of the pad after it to make width characters; s's text unchanged when it is already that wide.
(string-pad-right "ab" 4 #:with #\.)   ; "ab.."

Counts characters and never truncates, as string-pad-left does.

See also: string-pad-left, string-count

string-split

function ↑ Functions

(: string-split (-> string string (Vec string)))
(string-split s sep)

The fields between occurrences of a separator.

s
The string to split.
sep
The separator.
returns
The fields in order, empty ones kept. One more than the number of separators in s.
(string-split "a,,b" ",")   ; ["a" "" "b"]
(string-split "" ",")       ; [""]

Empty fields are kept; drop them with (vec-filter #(not (string-empty? &1)) parts). An empty separator gives the whole string as the one field. Each field has bytes of its own; string-split/slice shares them instead.

See also: string-split/slice, string-join

string-split/slice

function ↑ Functions

(: string-split/slice (-> string string (Vec string)))
(string-split/slice s sep)

The fields between occurrences of a separator, as slices of the string.

s
The string to split.
sep
The separator.
returns
The substrings produced by string-split, each sharing s's bytes.

No field is copied, and each keeps all of s alive while it is held. string-copy a field before keeping it.

See also: string-split, string-copy

string-join

function ↑ Functions

(: string-join (-> (Vec string) string string))
(string-join parts sep)

Strings joined with a separator between them.

parts
The strings, in order.
sep
What goes between two of them.
returns
The parts with sep between each two. No parts is the empty string.
(string-join ["a" "b" "c"] ", ")   ; "a, b, c"

Built through one builder, so it costs the length of the result.

See also: string-split, str

substring

function ↑ Functions

(: substring (-> string StringCursor StringCursor string))

The text between two cursors.

s
The string.
start
Where the text begins.
end
Where it ends, not included. Not before start.
returns
The characters from start up to end, with bytes of their own; s itself when that is all of it.
raises System.ArgumentException
When start is after end, or a cursor is not on a character boundary of s.
raises System.ArgumentOutOfRangeException
When a cursor is outside s.
(substring s (string-cursor-next s (string-cursor-start s))
             (string-cursor-end s))   ; all but the first character

See also: substring/slice, string-search, string-index, string-cursor-start

substring/slice

function ↑ Functions

(: substring/slice (-> string StringCursor StringCursor string))

The text between two cursors, as a slice of the string.

s
The string.
start
Where the text begins.
end
Where it ends, not included. Not before start.
returns
The characters from start up to end, sharing s's bytes.
raises System.ArgumentException
When start is after end, or a cursor is not on a character boundary of s.
raises System.ArgumentOutOfRangeException
When a cursor is outside s.

A slice is a string like any other: it equals, hashes and orders by its text, and goes anywhere a string goes. Two things set it apart.

Its cursors are its source’s. A cursor found in a slice, by string-search, string-index or a regex, is a position in the string it was taken from, and (string-cursor-start sl) is where the slice begins in it.

It keeps all of its source alive. A ten-byte slice of a megabyte keeps the megabyte. That is why the plain forms copy: a slice is for a scanner that cuts many short pieces out of one text and lets them go, not for keeping a piece.

See also: substring, string-copy

string-copy

function ↑ Functions

(: string-copy (-> string string))
(string-copy s)

The same text with bytes of its own.

s
The string.
returns
A string equal to s that shares no bytes; s itself when it already has its own.

What to do to a slice before holding on to it, so that it stops keeping the whole of its source alive.

The plain forms, such as substring, string-trim and string-replace, return their argument unchanged when no modification is needed. Given a slice, that return value is still the slice, so string-copy is the one way to be sure a string holds nothing more than its text.

See also: substring/slice, string-trim/slice, string-split/slice

string-cursor-start

function ↑ Functions

(: string-cursor-start (-> string StringCursor))

A cursor on the first character of a string.

s
The string.
returns
The cursor where s begins. For the empty string it is also the end.
(let loop ((c (string-cursor-start s)))
  (unless (string-cursor-end? s c)
    (println (char->string (string-cursor-ref s c)))
    (loop (string-cursor-next s c))))

A cursor is a position in a string, and what takes the place of an index: there is no string-ref, since reaching the n-th character of UTF-8 is O(n). A cursor costs what an int does, and stepping it is O(1).

It is opaque. There is no conversion between cursors and numbers: a cursor is made by string-cursor-start, string-cursor-end, a search, or a step, so it always rests on a character boundary.

It does not carry its string, so every operation takes the string as well. A cursor of a slice is a cursor of the string the slice was taken from, and is where the slice begins in it. A cursor used with another string is caught only when it falls outside that string or inside one of its characters.

(:for ch s) walks a string faster than a cursor loop does; a cursor is for when the positions are wanted.

See also: string-cursor-end, string-cursor-next, string-cursor-ref

string-cursor-end

function ↑ Functions

(: string-cursor-end (-> string StringCursor))

The past-the-end cursor of a string.

s
The string.
returns
The cursor after the last character: the bound a traversal stops at.

See also: string-cursor-end?, string-cursor-start, string-cursor-prev

string-cursor-end?

function ↑ Functions

(: string-cursor-end? (-> string StringCursor bool))

Whether a cursor has reached the end of its string.

s
The string.
c
A cursor of s.
returns
#t when c is the past-the-end cursor, and there is no character at it.

See also: string-cursor-end, string-cursor-ref

string-cursor-ref

function ↑ Functions

(: string-cursor-ref (-> string StringCursor char))

The character at a cursor.

s
The string.
c
A cursor of s, not at the end.
returns
The character c is on.
raises System.ArgumentOutOfRangeException
When c is at the end of s, or outside it.
raises System.ArgumentException
When c is not on a character boundary of s, as a cursor from another string may be.

Guard it with string-cursor-end?.

See also: string-cursor-ref+next, string-cursor-end?

string-cursor-next

function ↑ Functions

(: string-cursor-next (-> string StringCursor StringCursor))

The cursor on the next character.

s
The string.
c
A cursor of s, not at the end.
returns
The cursor after the character at c, which is the end after the last one.
raises System.ArgumentOutOfRangeException
When c is at the end of s, or outside it.
raises System.ArgumentException
When c is not on a character boundary of s.

Steps over all the bytes the character takes, so it lands on the next character whatever its width.

See also: string-cursor-prev, string-cursor-ref+next

string-cursor-prev

function ↑ Functions

(: string-cursor-prev (-> string StringCursor StringCursor))

The cursor on the previous character.

s
The string.
c
A cursor of s, not at the start.
returns
The cursor on the character before c.
raises System.ArgumentOutOfRangeException
When c is at the start of s, or outside it.

O(1): it steps back over at most three continuation bytes, and decodes nothing.

See also: string-cursor-next, string-cursor-end, string-fold-right

string-cursor-ref+next

function ↑ Functions

(: string-cursor-ref+next (-> string StringCursor (Tuple char StringCursor)))

The character at a cursor and the cursor after it, in one call.

s
The string.
c
A cursor of s, not at the end.
returns
A tuple of the character at c and the cursor on the next one.
raises System.ArgumentOutOfRangeException
When c is at the end of s, or outside it.
raises System.ArgumentException
When c is not on a character boundary of s.
(def (Tuple ch next) (string-cursor-ref+next s c))

Reading the byte at c provides both the character and the next cursor in a single operation, whereas string-cursor-ref and string-cursor-next each read and validate independently. The tuple is a ValueTuple and does not allocate.

See also: string-cursor-ref, string-cursor-next

string-cursor=?

function ↑ Functions

(: string-cursor=? (-> StringCursor StringCursor bool))
(string-cursor=? a b)

Whether two cursors are at the same position.

a
A cursor.
b
A cursor of the same string.
returns
#t when they are equal.

The comparisons are aliases for =, < and the rest, which work on cursors directly. Cursors of two different strings compare without complaint and mean nothing; those of a slice and of its source are of one string.

See also: string-cursor<?, string-cursor-start

string-cursor<?

function ↑ Functions

(: string-cursor<? (-> StringCursor StringCursor bool))
(string-cursor<? a b)

Whether one cursor is before another.

a
A cursor.
b
A cursor of the same string.
returns
#t when a is before b.

See also: string-cursor<=?, string-cursor>?, string-cursor=?

string-cursor>?

function ↑ Functions

(: string-cursor>? (-> StringCursor StringCursor bool))
(string-cursor>? a b)

Whether one cursor is after another.

a
A cursor.
b
A cursor of the same string.
returns
#t when a is after b.

See also: string-cursor>=?, string-cursor<?, string-cursor=?

string-cursor<=?

function ↑ Functions

(: string-cursor<=? (-> StringCursor StringCursor bool))
(string-cursor<=? a b)

Whether one cursor is before another or at it.

a
A cursor.
b
A cursor of the same string.
returns
#t when a is not after b.

See also: string-cursor<?, string-cursor>=?, string-cursor=?

string-cursor>=?

function ↑ Functions

(: string-cursor>=? (-> StringCursor StringCursor bool))
(string-cursor>=? a b)

Whether one cursor is after another or at it.

a
A cursor.
b
A cursor of the same string.
returns
#t when a is not before b.

See also: string-cursor>?, string-cursor<=?, string-cursor=?

string-fold

function ↑ Functions

(: string-fold (-> (-> char %a %a) %a string %a))
(string-fold f init s)

Folds a function over the characters of a string, from the start.

f
Called with each character and the accumulator, returning the next accumulator value.
init
The accumulator before the first character.
s
The string.
returns
The accumulator after the last character; init for the empty string.
(string-fold (fun (c n) (if (char=? c #\a) (+ n 1) n)) 0 "banana")   ; 3

See also: string-fold-right, string-for-each, fold

string-fold-right

function ↑ Functions

(: string-fold-right (-> (-> char %a %a) %a string %a))
(string-fold-right f init s)

Folds a function over the characters of a string, from the end.

f
Called with each character and the accumulator, returning the next accumulator value.
init
The accumulator before the last character.
s
The string.
returns
The accumulator after the first character; init for the empty string.
(string-fold-right cons Nil "abc")   ; (#\a #\b #\c)

It walks backwards with string-cursor-prev, so it is a loop and not one stack frame per character.

See also: string-fold, string->list

string-for-each

function ↑ Functions

(: string-for-each (-> (-> char void) string void))
(string-for-each f s)

Calls a function on each character of a string, in order.

f
Called once per character, for its effect.
s
The string.

See also: string-fold, string-walk

string-walk

function ↑ Functions

(: string-walk (-> string StringWalk))

A walk on the first character of a string.

s
The string.
returns
A walk on s's first character, or one already done for the empty string.
(let loop ((w (string-walk s)))
  (unless (string-walk-done? w)
    (println (char->string (string-walk-current w)))
    (loop (string-walk-next w))))

The four string-walk functions are exported because the Iterable impl for string is inlined where it is used, and reaches them there. A (:for ch s) clause is the ordinary way to use them.

See also: string-walk-done?, string-walk-current, string-walk-next, StringWalk

string-walk-done?

function ↑ Functions

(: string-walk-done? (-> StringWalk bool))

Whether a walk has passed the last character.

w
The walk.
returns
#t when there is no character left.

See also: string-walk, string-walk-current

string-walk-current

function ↑ Functions

(: string-walk-current (-> StringWalk char))

The character a walk is on.

w
The walk, not done.
returns
The character, already decoded.
raises System.InvalidOperationException
When the walk is done.

See also: string-walk-done?, string-walk-next

string-walk-next

function ↑ Functions

(: string-walk-next (-> StringWalk StringWalk))

The walk on the next character.

w
The walk.
returns
A walk on the character after w's, decoded; done after the last one. A completed walk returns itself.

See also: string-walk, string-walk-done?

string->list

function ↑ Functions

(: string->list (-> string (List char)))
(string->list s)

The characters of a string, as a list.

s
The string.
returns
Its characters in order.

See also: list->string, string->vec, string-fold-right

string->vec

function ↑ Functions

(: string->vec (-> string (Vec char)))
(string->vec s)

The characters of a string, as a vec.

s
The string.
returns
Its characters in order.

See also: string->list, string-for-each

string-reverse

function ↑ Functions

(: string-reverse (-> string string))
(string-reverse s)

A string with its characters in reverse order.

s
The string.
returns
The characters of s, last first. The same number of bytes as s.
(string-reverse "a😀b")   ; "b😀a"

By character, not by byte, so a character of several bytes comes back whole.

See also: string->list

string->int

function ↑ Functions

(: string->int (-> string int))
(string->int s)

Parses a string into an int.

s
Decimal digits, with an optional sign.
returns
The parsed integer value.
(string->int "-42")   ; -42

Invariant culture, so it reads what int->string writes on any machine. Whitespace at either end is allowed. Text that is not such a number throws, as .NET’s int.Parse does: a FormatException, or an OverflowException when the number does not fit.

See also: string->long, string->double, int->string

string->long

function ↑ Functions

(: string->long (-> string long))
(string->long s)

Parses a string into a long.

s
Decimal digits, with an optional sign.
returns
The parsed integer value.
(string->long "-9000000000")   ; -9000000000

As string->int, for 64 bits. Invariant culture, so it reads what long->string writes on any machine. Whitespace at either end is allowed. Text that is not such a number throws a FormatException, and a number that does not fit throws an OverflowException.

See also: string->int, long->string

string->double

function ↑ Functions

(: string->double (-> string double))
(string->double s)

Parses a string into a double.

s
A sign, digits, a decimal point and an exponent.
returns
The parsed double value.
(string->double "1.5e3")   ; 1500

Invariant culture, so the decimal point is always . and it reads what double->string writes on any machine. There are no thousands separators. Text that is not such a number throws, as .NET’s double.Parse does.

See also: string->int, double->string

string->decimal

function ↑ Functions

(: string->decimal (-> string decimal))
(string->decimal s)

Parses a string into a decimal.

s
A sign, digits, a decimal point and an exponent.
returns
The parsed decimal value, with the scale the text has.
(string->decimal "1.50")   ; 1.50M

Invariant culture, as string->double. Text that is not such a number, or that is too large for a decimal, throws.

See also: string->double, decimal->string

string->bigint

function ↑ Functions

(: string->bigint (-> string bigint))
(string->bigint s)

Parses a string into a bigint.

s
A sign and digits, as many as there are.
returns
The parsed bigint value.
(string->bigint "123456789012345678901234567890")

Invariant culture. Text that is not such a number throws.

See also: string->int, bigint->string

string->int128

function ↑ Functions

(: string->int128 (-> string int128))
(string->int128 s)

Parses a string into an int128.

s
A sign and digits.
returns
The parsed int128 value.

Invariant culture. Text that is not such a number, or one outside the range of an int128, throws.

See also: string->bigint, int128->string

string->uint128

function ↑ Functions

(: string->uint128 (-> string uint128))
(string->uint128 s)

Parses a string into a uint128.

s
Digits.
returns
The parsed uint128 value.

Invariant culture. Text that is not such a number, or one outside the range of a uint128, throws.

See also: string->int128, uint128->string

bytes->string

function ↑ Functions

(: bytes->string (-> (Array byte) (#:encoding Encoding) (#:start int) (#:end int) (#:replace (Option char)) string))
(bytes->string bytes #:encoding clr-utf-8 #:start 0 #:end (array-length bytes) #:replace None)

The text some bytes encode.

bytes
The bytes.
#:encoding
What they are in: utf-8, the default, or any value from (text encodings).
#:start
The first byte to decode: 0 by default.
#:end
One past the last byte to decode: the end of the array by default.
#:replace
None, the default, to fail on bytes that do not decode; (Some c) to put c in their place, once per invalid sequence.
returns
The text of the bytes from start to end.
(bytes->string (string->bytes "blåbär"))              ; "blåbär"
(bytes->string bs #:encoding windows-1252)            ; with (text encodings)
(bytes->string bs #:start 4 #:end 8)
(bytes->string bs #:replace (Some #\\xFFFD))           ; never fails

Strict, as Racket’s bytes->string/utf-8 is: bytes that do not decode throw an ArgumentException naming their offset and the bytes themselves. A string is UTF-8, so from UTF-8 this checks the bytes and copies them; the string never shares the array. A byte order mark is not skipped: it is the character U+FEFF. A range outside the array throws.

See also: string->bytes, Encoding

string->bytes

function ↑ Functions

(: string->bytes (-> string (#:encoding Encoding) (#:replace (Option char)) (Array byte)))
(string->bytes s #:encoding clr-utf-8 #:replace None)

The bytes that encode a string.

s
The string.
#:encoding
What to encode it in: utf-8, the default, or any value from (text encodings).
#:replace
None, the default, to fail on a character the encoding lacks; (Some c) to encode c in its place.
returns
A new array of the bytes, without a byte order mark.
(string->bytes "blåbär")                          ; 8 bytes of UTF-8
(string->bytes "blåbär" #:encoding iso-8859-1)    ; 6 bytes, with (text encodings)
(string->bytes "ok ✓" #:encoding us-ascii #:replace (Some #\\?))   ; "ok ?"

Strict: a character the encoding has no bytes for throws an ArgumentException naming it and its offset in the string. The replacement character must itself be in the encoding, and stands in for one character, even one that UTF-16 would write as two units. To UTF-8 this is a copy of the string’s own bytes.

See also: bytes->string, Encoding

string-take

function ↑ Functions

(: string-take (-> string int string))
(string-take s n)

The first n characters of a string.

s
The string.
n
How many characters, 0 or more.
returns
The first n characters, with bytes of their own; all of s when it has fewer.
(string-take "hello" 2)    ; "he"
(string-take "hi" 10)      ; "hi"

Characters, not bytes: (string-take "héllo" 2) is "hé". The cursors walk n characters from the start, so the cost is in n, not in the length of s. A negative n is refused with a panic.

See also: string-drop, string-take-right, string-take/slice, substring

string-drop

function ↑ Functions

(: string-drop (-> string int string))
(string-drop s n)

A string without its first n characters.

s
The string.
n
How many characters, 0 or more.
returns
The characters after the first n, with bytes of their own; the empty string when s has n or fewer.
(string-drop "L68" 1)              ; "68"
(string->int (string-drop "L68" 1)) ; 68

The cost is in n, as for string-take. A negative n is refused with a panic.

See also: string-take, string-drop-right, string-drop/slice

string-take-right

function ↑ Functions

(: string-take-right (-> string int string))
(string-take-right s n)

The last n characters of a string.

s
The string.
n
How many characters, 0 or more.
returns
The last n characters, with bytes of their own; all of s when it has fewer.
(string-take-right "file.txt" 3)   ; "txt"

The cursors walk n characters back from the end. A negative n is refused with a panic.

See also: string-drop-right, string-take

string-drop-right

function ↑ Functions

(: string-drop-right (-> string int string))
(string-drop-right s n)

A string without its last n characters.

s
The string.
n
How many characters, 0 or more.
returns
The characters before the last n, with bytes of their own; the empty string when s has n or fewer.
(string-drop (string-drop-right "(1,3)" 1) 1)   ; "1,3"

The cursors walk n characters back from the end. A negative n is refused with a panic.

See also: string-take-right, string-drop

string-take/slice

function ↑ Functions

(: string-take/slice (-> string int string))
(string-take/slice s n)

The first n characters of a string, sharing its bytes.

s
The string.
n
How many characters, 0 or more.
returns
The first n characters, as a slice of s.

As string-take, without a copy. The slice keeps all of s alive.

See also: string-take, substring/slice

string-drop/slice

function ↑ Functions

(: string-drop/slice (-> string int string))
(string-drop/slice s n)

A string without its first n characters, sharing its bytes.

s
The string.
n
How many characters, 0 or more.
returns
The characters after the first n, as a slice of s.

As string-drop, without a copy. The slice keeps all of s alive.

See also: string-drop, substring/slice

string-take-right/slice

function ↑ Functions

(: string-take-right/slice (-> string int string))
(string-take-right/slice s n)

The last n characters of a string, sharing its bytes.

s
The string.
n
How many characters, 0 or more.
returns
The last n characters, as a slice of s.

As string-take-right, without a copy. The slice keeps all of s alive.

See also: string-take-right, substring/slice

string-drop-right/slice

function ↑ Functions

(: string-drop-right/slice (-> string int string))
(string-drop-right/slice s n)

A string without its last n characters, sharing its bytes.

s
The string.
n
How many characters, 0 or more.
returns
The characters before the last n, as a slice of s.

As string-drop-right, without a copy. The slice keeps all of s alive.

See also: string-drop-right, substring/slice

string-cursor-forward

function ↑ Functions

(: string-cursor-forward (-> string StringCursor int StringCursor))
(string-cursor-forward s c n)

The cursor n characters after another.

s
The string.
c
A cursor of s.
n
How many characters, 0 or more.
returns
The cursor after the n characters from c.
raises System.ArgumentOutOfRangeException
When there are fewer than n characters after c.

string-cursor-next n times. It raises where that does, at the end of s; string-drop is the form that stops at the end instead. A negative n is refused with a panic.

See also: string-cursor-back, string-cursor-next

string-cursor-back

function ↑ Functions

(: string-cursor-back (-> string StringCursor int StringCursor))
(string-cursor-back s c n)

The cursor n characters before another.

s
The string.
c
A cursor of s.
n
How many characters, 0 or more.
returns
The cursor n characters before c.
raises System.ArgumentOutOfRangeException
When there are fewer than n characters before c.

string-cursor-prev n times. A negative n is refused with a panic.

See also: string-cursor-forward, string-cursor-prev

string-split-once

function ↑ Functions

(: string-split-once (-> string string (Option (Tuple string string))))
(string-split-once s sep)

The text before and after the first occurrence of a separator.

s
The string.
sep
The separator.
returns
(Some (Tuple before after)), each with bytes of its own, or None when sep is not in s.
(string-split-once "key: value" ": ")   ; (Some (key, value))
(string-split-once "10-20-30" "-")      ; (Some (10, 20-30))
(string-split-once "none" "-")          ; None

Ordinal, as string-search. Only the first occurrence splits: the rest of s, separators and all, is the second part. An empty separator is found at the start, so the first part is empty.

See also: string-split, string-search, string-split-once/slice

string-split-once/slice

function ↑ Functions

(: string-split-once/slice (-> string string (Option (Tuple string string))))
(string-split-once/slice s sep)

The text before and after the first occurrence of a separator, sharing the string’s bytes.

s
The string.
sep
The separator.
returns
(Some (Tuple before after)), as slices of s, or None when sep is not in s.

As string-split-once, without a copy. The slices keep all of s alive.

See also: string-split-once, string-split/slice

char->int

function ↑ Functions

(: char->int (-> char int))

The codepoint of a character.

c
The character.
returns
Its Unicode scalar value, from 0 to #x10FFFF, never a surrogate.
(char->int #\a)    ; 97

A codepoint rather than a UTF-16 code unit: a character outside the Basic Multilingual Plane returns its full scalar value, not a surrogate. char->integer is the same function under R6RS’s name.

See also: int->char, char->integer, char->string

char->integer

function ↑ Functions

(: char->integer (-> char int))
(char->integer c)

The codepoint of a character, under R6RS’s name.

c
The character.
returns
Its Unicode scalar value.

See also: char->int, integer->char

int->char

function ↑ Functions

(: int->char (-> int char))

The character with a given codepoint.

n
A Unicode scalar value: from 0 to #x10FFFF, outside the surrogates #xD800 to #xDFFF.
returns
The character.
raises System.ArgumentOutOfRangeException
When n is not a Unicode scalar value: negative, a surrogate, or above #x10FFFF.
(int->char 955)    ; #\λ

See also: char->int, integer->char

integer->char

function ↑ Functions

(: integer->char (-> int char))
(integer->char n)

The character with a given codepoint, under R6RS’s name.

n
A Unicode scalar value.
returns
The character.
raises System.ArgumentOutOfRangeException
When n is not a Unicode scalar value, as for int->char.

See also: int->char, char->integer

char->string

function ↑ Functions

(: char->string (-> char string))

A string of one character.

c
The character.
returns
The one-character string.

For a character outside ASCII the string is longer than one in string-length, which counts UTF-8 bytes: an astral character gives a string of string-length 4 and string-count 1.

This is the way from a char to a .NET method that wants text: a Bjolang char is a codepoint, not a C# char.

See also: char->int, string-length, string-count

char=?

function ↑ Functions

(: char=? (-> char char bool))
(char=? a b)

Whether two characters are the same codepoint.

a
The first character.
b
The second.
returns
#t when a and b are the same character.

Binary, where R6RS’s is n-ary. = works on characters directly.

See also: char-ci=?, char<?

char<?

function ↑ Functions

(: char<? (-> char char bool))
(char<? a b)

Whether one character comes before another, by codepoint.

a
The first character.
b
The second.
returns
#t when a's codepoint is less than b's.

Ordering is by codepoint, so a character above U+FFFF sorts after U+FFFD rather than by its leading surrogate.

Binary, where R6RS’s is n-ary. The operators work on characters, so (< a b c) chains as it does for numbers.

See also: char<=?, char>?, char-ci<?

char>?

function ↑ Functions

(: char>? (-> char char bool))
(char>? a b)

Whether one character comes after another, by codepoint.

a
The first character.
b
The second.
returns
#t when a's codepoint is greater than b's.

See also: char>=?, char<?, char-ci>?

char<=?

function ↑ Functions

(: char<=? (-> char char bool))
(char<=? a b)

Whether one character comes before another or is the same, by codepoint.

a
The first character.
b
The second.
returns
#t when a's codepoint is not greater than b's.

See also: char<?, char>=?, char-ci<=?

char>=?

function ↑ Functions

(: char>=? (-> char char bool))
(char>=? a b)

Whether one character comes after another or is the same, by codepoint.

a
The first character.
b
The second.
returns
#t when a's codepoint is not less than b's.

See also: char>?, char<=?, char-ci>=?

char-ci=?

function ↑ Functions

(: char-ci=? (-> char char bool))
(char-ci=? a b)

Whether two characters are the same, ignoring case.

a
The first character.
b
The second.
returns
#t when a and b are the same after char-foldcase.
(char-ci=? #\a #\A)    ; #t

Both sides go through char-foldcase and are then compared by codepoint, as every char-ci comparison does. Binary, where R6RS’s is n-ary.

See also: char=?, char-foldcase

char-ci<?

function ↑ Functions

(: char-ci<? (-> char char bool))
(char-ci<? a b)

Whether one character comes before another, ignoring case.

a
The first character.
b
The second.
returns
#t when a's folded codepoint is less than b's.

See also: char<?, char-foldcase

char-ci>?

function ↑ Functions

(: char-ci>? (-> char char bool))
(char-ci>? a b)

Whether one character comes after another, ignoring case.

a
The first character.
b
The second.
returns
#t when a's folded codepoint is greater than b's.

See also: char>?, char-foldcase

char-ci<=?

function ↑ Functions

(: char-ci<=? (-> char char bool))
(char-ci<=? a b)

Whether one character comes before another or is the same, ignoring case.

a
The first character.
b
The second.
returns
#t when a's folded codepoint is not greater than b's.

See also: char<=?, char-foldcase

char-ci>=?

function ↑ Functions

(: char-ci>=? (-> char char bool))
(char-ci>=? a b)

Whether one character comes after another or is the same, ignoring case.

a
The first character.
b
The second.
returns
#t when a's folded codepoint is not less than b's.

See also: char>=?, char-foldcase

char-upcase

function ↑ Functions

(: char-upcase (-> char char))

The uppercase form of a character.

c
The character.
returns
Its uppercase mapping, or c itself when it has none.

Uses the invariant culture mapping, so the result does not depend on the machine’s locale. A mapping is one character to one character: ß upcases to itself, not to SS.

See also: char-downcase, char-titlecase, char-upper-case?

char-downcase

function ↑ Functions

(: char-downcase (-> char char))

The lowercase form of a character.

c
The character.
returns
Its lowercase mapping, or c itself when it has none.

The invariant culture’s mapping. For comparing without regard to case, use char-foldcase.

See also: char-upcase, char-foldcase, char-lower-case?

char-titlecase

function ↑ Functions

(: char-titlecase (-> char char))

The titlecase form of a character.

c
The character.
returns
Its titlecase mapping, or c itself when it has none.
(char-titlecase #\dž)    ; #\Dž
(char-titlecase #\a)    ; #\A

The same as char-upcase except for the handful of Latin digraphs Unicode gives a distinct titlecase form: dž and DŽ both evaluate to Dž. It goes through the invariant culture’s string title-casing, which costs a small allocation, so char-upcase is the one to use unless the digraphs matter.

See also: char-upcase, char-title-case?

char-foldcase

function ↑ Functions

(: char-foldcase (-> char char))

A character with its case folded, for comparing without regard to case.

c
The character.
returns
Its simple case fold.

Close to Unicode’s simple case folding, one character to one character, as R6RS specifies it. It is the invariant lowercase mapping, which differs from the simple fold for a few characters that are already lowercase: ς, ſ and µ stay as they are, where the fold gives σ, s and μ, so (char-ci=? #\ς #\σ) is #f. ß stays as it is, which the simple fold does too.

Every char-ci comparison folds both sides with it.

See also: char-ci=?, char-downcase

char-alphabetic?

function ↑ Functions

(: char-alphabetic? (-> char bool))

Whether a character is a letter.

c
The character.
returns
#t when c is in one of the letter categories: Lu, Ll, Lt, Lm or Lo.

Classified by codepoint, so supplementary letters return #t.

See also: char-numeric?, char-general-category

char-numeric?

function ↑ Functions

(: char-numeric? (-> char bool))

Whether a character is a number of any kind.

c
The character.
returns
#t when c is in category Nd, Nl or No.

Wider than decimal digits: ½ and Ⅶ are numeric. digit-value returns a value only for decimal digits.

See also: digit-value, char-alphabetic?

char-whitespace?

function ↑ Functions

(: char-whitespace? (-> char bool))

Whether a character is white space.

c
The character.
returns
#t for the separators (Zs, Zl, Zp) and the control characters tab, line feed, vertical tab, form feed, carriage return and U+0085.

The definition string-trim and its neighbours use.

See also: char-general-category

char-upper-case?

function ↑ Functions

(: char-upper-case? (-> char bool))

Whether a character is an uppercase letter.

c
The character.
returns
#t when c is in category Lu.

See also: char-lower-case?, char-title-case?, char-upcase

char-lower-case?

function ↑ Functions

(: char-lower-case? (-> char bool))

Whether a character is a lowercase letter.

c
The character.
returns
#t when c is in category Ll.

See also: char-upper-case?, char-downcase

char-title-case?

function ↑ Functions

(: char-title-case? (-> char bool))

Whether a character is a titlecase letter.

c
The character.
returns
#t when c is in category Lt, such as Dž.

See also: char-titlecase, char-upper-case?

digit-value

function ↑ Functions

(: digit-value (-> char (Option int)))

The value of a decimal digit.

c
The character.
returns
(Some n), n from 0 to 9, when c is a decimal digit (category Nd); None otherwise.
(digit-value #\7)    ; (Some 7)
(digit-value #\٣)    ; (Some 3), ARABIC-INDIC DIGIT THREE
(digit-value #\½)    ; None

Narrower than char-numeric?: ½ is numeric and has no digit value. Any decimal digit counts, not only 0 to 9 of ASCII.

See also: char-numeric?

char-general-category

function ↑ Functions

(: char-general-category (-> char Symbol))

The Unicode general category of a character.

c
The character.
returns
The two-letter category as a symbol: 'Lu, 'Ll, 'Nd, 'Zs and the rest.
(char-general-category #\a)        ; 'Ll
(char-general-category #\space)    ; 'Zs

One of the thirty categories R6RS names: Lu Ll Lt Lm Lo, Mn Mc Me, Nd Nl No, Pc Pd Ps Pe Pi Pf Po, Sm Sc Sk So, Zs Zl Zp, Cc Cf Cs Co and Cn. An unassigned codepoint returns 'Cn. A symbol, so it is compared with = or eq? at the cost of a reference comparison.

See also: char-alphabetic?, char-numeric?, char-whitespace?

keyword?

function ↑ Functions

(: keyword? (-> %a bool))

Whether a value is a keyword.

x
Any value.
returns
#t when x is a Keyword at run time.

See also: symbol?, string->keyword

keyword->string

function ↑ Functions

(: keyword->string (-> Keyword string))

The name of a keyword.

k
The keyword.
returns
Its name, without the colon: "foo" for :foo.

See also: string->keyword, symbol->string

string->keyword

function ↑ Functions

(: string->keyword (-> string Keyword))

The keyword with a given name.

s
The name, without the colon.
returns
The interned keyword corresponding to s.

Keywords are interned, so (= a b) on two of them is a reference comparison.

See also: keyword->string, string->symbol

symbol?

function ↑ Functions

(: symbol? (-> %a bool))

Whether a value is a symbol.

x
Any value.
returns
#t when x is a Symbol at run time.

See also: keyword?, string->symbol

symbol->string

function ↑ Functions

(: symbol->string (-> Symbol string))

The name of a symbol.

sym
The symbol.
returns
Its name: "foo" for 'foo.

See also: string->symbol, keyword->string

string->symbol

function ↑ Functions

(: string->symbol (-> string Symbol))

The symbol with a given name.

s
The name.
returns
The interned symbol corresponding to s.

Symbols are interned, so (= a b) on two of them is a reference comparison, and either can be a map key.

See also: symbol->string, string->keyword

stringbuilder-empty

function ↑ Functions

(: stringbuilder-empty (-> StringBuilder))

A new, empty string builder.

returns
A builder holding no text.
(def b (stringbuilder-empty))
(stringbuilder-add-string! b "ab")
(stringbuilder-add! b #\c)
(stringbuilder->string b)    ; "abc"

A growable UTF-8 buffer, and the accumulator behind the stringing collector. The append operations mutate the builder in place: the builder remains the same object throughout.

Use one, or a (:acc out (stringing c)) clause, rather than string-append in a loop, which copies the whole string at every step. A builder also carries no colour, where writing to a string port gives the writing function a suspending copy.

See also: stringbuilder-add!, stringbuilder-add-string!, stringbuilder->string

stringbuilder-add!

function ↑ Functions

(: stringbuilder-add! (-> StringBuilder char void))

Adds a character to the end of a string builder, in place.

b
The builder.
c
The character, encoded as UTF-8.

See also: stringbuilder-add-string!, stringbuilder-add-code!

stringbuilder-add-string!

function ↑ Functions

(: stringbuilder-add-string! (-> StringBuilder string void))

Adds a string to the end of a string builder, in place.

b
The builder.
s
The string.

See also: stringbuilder-add!

stringbuilder-add-code!

function ↑ Functions

(: stringbuilder-add-code! (-> StringBuilder int void))

Adds one UTF-8 byte to the end of a string builder, in place.

b
The builder.
n
The byte, from 0 to 255.

For a scanner that copies its input a byte at a time and already holds the number: it skips decoding and re-encoding a character.

A number outside 0 to 255 raises System.ArgumentOutOfRangeException. Whether the bytes form whole characters is not checked here: stringbuilder->string checks that, and raises if they do not.

See also: stringbuilder-code-ref, stringbuilder-add!, stringbuilder->string

stringbuilder-add-unit!

function ↑ Functions

(: stringbuilder-add-unit! (-> StringBuilder int void))

Adds one UTF-16 code unit to the end of a string builder, in place.

b
The builder.
n
The code unit, from 0 to 65535.

For a reader taking units from a .NET text port. A surrogate pair given in two calls, high then low, becomes its one character. A surrogate left unpaired makes stringbuilder->string raise. A number outside 0 to 65535 raises System.ArgumentOutOfRangeException.

See also: stringbuilder-add!, stringbuilder->string

stringbuilder-length

function ↑ Functions

(: stringbuilder-length (-> StringBuilder int))

How much text a string builder holds, in bytes.

b
The builder.
returns
The number of UTF-8 bytes added so far, not characters.

See also: stringbuilder-code-ref, string-length

stringbuilder-code-ref

function ↑ Functions

(: stringbuilder-code-ref (-> StringBuilder int int))

One byte of what a string builder holds.

b
The builder.
i
The byte index, from 0, less than stringbuilder-length.
returns
The byte at i, from 0 to 255.
raises System.ArgumentOutOfRangeException
When i is negative or not less than the builder's length.

The counterpart of stringbuilder-add-code!, for a scanner that looks back at what it wrote. Indices are bytes, not characters.

See also: stringbuilder-add-code!, stringbuilder-length

stringbuilder-clear!

function ↑ Functions

(: stringbuilder-clear! (-> StringBuilder void))

Empties a string builder for reuse, in place.

b
The builder.

The builder keeps the buffer it has grown, so a reader that builds many short strings does not pay for a new builder each time. Strings already made from it are unaffected.

See also: stringbuilder-empty

stringbuilder=?

function ↑ Functions

(: stringbuilder=? (-> StringBuilder string bool))

Whether a string builder holds exactly a given text.

b
The builder.
s
The text to compare with.
returns
#t when b's bytes are s's bytes.

Compares without building a string, which lets a reader ask whether the name it just buffered is one it has already interned without paying for the allocation.

See also: stringbuilder->string

stringbuilder->string

function ↑ Functions

(: stringbuilder->string (-> StringBuilder string))

The text a string builder holds, as a string.

b
The builder.
returns
A copy of the text so far.
raises System.InvalidOperationException
When bytes from stringbuilder-add-code!, or a surrogate from stringbuilder-add-unit! left unpaired, do not form valid UTF-8.

The string is a copy: the builder keeps its text and can go on growing, and what is added afterwards does not change the string.

See also: stringbuilder-empty, stringbuilder-clear!

file-read-text

function ↑ Functions

(: file-read-text (-> string string))
(file-read-text path)

The whole of a file, as one string.

path
The file to read.
returns
Everything the file holds.

For a file that fits in memory; a port reads one that does not. Opening goes through the FS effect’s open-read-stream, and an Err from it is raised, as the .NET methods raise: wrap the call in try for a Result. The file is closed before this returns.

A bjoroutine calling it awaits the file rather than parking its thread.

See also: file-read-lines, file-read-bytes, file-write-text, open-input-file

file-write-text

function ↑ Functions

(: file-write-text (-> string string void))
(file-write-text path contents)

Writes a string to a file, replacing what it held.

path
The file to write. Created if it is missing, emptied if it is there.
contents
The text to write.

Opened with Truncate through the FS effect; an error opening it is raised. The text is flushed before the file is closed, and a bjoroutine awaits the write.

See also: file-append-text, file-write-lines, file-read-text

file-append-text

function ↑ Functions

(: file-append-text (-> string string void))
(file-append-text path contents)

Writes a string after what a file holds.

path
The file to add to. Created if it is missing.
contents
The text to add.

Opened with Append through the FS effect; an error opening it is raised.

See also: file-write-text, file-append-bytes

file-read-lines

function ↑ Functions

(: file-read-lines (-> string (#:mode LineMode) (Vec string)))
(file-read-lines path #:mode Any)

The lines of a file, without their line ends.

path
The file to read.
#:mode
What ends a line, as for read-line: Any by default.
returns
One string per line, in order.

By default "\n", "\r\n" and a lone "\r" each end a line, as read-line reads them, a last line needs none, and a final line end makes no empty line after it. The whole file is read before this returns; file-read-lines/seq pulls the lines lazily instead. An error opening the file is raised.

See also: file-write-lines, file-read-lines/seq, file-read-text, LineMode

file-write-lines

function ↑ Functions

(: file-write-lines (-> string (Vec string) void))
(file-write-lines path lines)

Writes lines to a file, each followed by a newline, replacing what it held.

path
The file to write. Created if it is missing, emptied if it is there.
lines
The lines, without line ends.

Every line is followed by "\n", the last one too, on every OS, so the same lines make the same bytes wherever they are written. file-read-lines gives them back as long as no line holds a line end of its own.

See also: file-read-lines, file-write-text

file-read-bytes

function ↑ Functions

(: file-read-bytes (-> string (Array byte)))
(file-read-bytes path)

The whole of a file, as bytes.

path
The file to read.
returns
A new array holding everything the file holds.

Opened through the FS effect’s open-read-stream; an Err from it is raised.

See also: file-write-bytes, file-read-text

file-write-bytes

function ↑ Functions

(: file-write-bytes (-> string (Array byte) void))
(file-write-bytes path bytes)

Writes bytes to a file, replacing what it held.

path
The file to write. Created if it is missing, emptied if it is there.
bytes
What to write.

See also: file-append-bytes, file-read-bytes

file-append-bytes

function ↑ Functions

(: file-append-bytes (-> string (Array byte) void))
(file-append-bytes path bytes)

Writes bytes after what a file holds.

path
The file to add to. Created if it is missing.
bytes
What to add.

See also: file-write-bytes, file-append-text

file-copy

function ↑ Functions

(: file-copy (-> string string (#:mode WriteMode) void))
(file-copy from to #:mode CreateNew)

Copies a file.

from
The file to copy.
to
Where the copy goes.
#:mode
How to is written: CreateNew, the default, Truncate or Append.
raises System.IO.IOException
When from and to are the same path.
(file-copy "a.txt" "b.txt")                    ; fails if b.txt exists
(file-copy "a.txt" "b.txt" #:mode Truncate)    ; replaces it

CreateNew, the default, fails if to exists, so a copy never loses a file by accident; it is the one function whose WriteMode does not default to Truncate. Truncate replaces to, and Append adds to it. The source is opened first, so a missing one leaves to as it was. A copy onto its own path, compared after path-absolute, is refused.

to may be the source under another name, a link say, and the text of the paths cannot tell. So nothing that could empty the source is ever opened: Truncate copies into a new file beside to and moves it over to with MoveReplace, which replaces a link there rather than writing through it, and Append copies the length the source had when it was opened, so a file appended to itself grows once and stops. The copy is a new file, with a modified time of its own.

See also: file-move, file-read-bytes

file-info

function ↑ Functions

(: file-info (-> string (Option FsInfo)))
(file-info path)

What a path names: its kind, size, last write and whether it is a link.

path
The path to ask about.
returns
None when the path names nothing.
(match (file-info "notes.txt")
  ((Some info) (record-ref info size))
  (None 0L))

Dispatched through the FS effect’s fs-info operation. A symbolic link’s size and time are those of what it leads to, which is what reading it reads; link? says it is one. With (std datetime), (unix-milliseconds->instant (record-ref info modified-ms)) converts the timestamp to an (Option Instant).

A path that is no path at all, "" say, is None rather than an error.

See also: FsInfo, file-exists?, directory-exists?, fs-info

file-exists?

function ↑ Functions

(: file-exists? (-> string bool))
(file-exists? path)

Whether a path names a file.

path
The path to ask about.
returns
#t for a file, #f for a directory or for nothing.

See also: directory-exists?, file-info

file-delete

function ↑ Functions

(: file-delete (-> string void))
(file-delete path)

Deletes a file.

path
The file to delete.

A missing file is not an error. Through the FS effect’s fs-delete-file; an Err from it is raised.

See also: directory-delete, fs-delete-file

file-move

function ↑ Functions

(: file-move (-> string string (#:mode MoveMode) void))
(file-move from to #:mode MoveNew)

Moves or renames a file or a directory.

from
What to move.
to
Its new path.
#:mode
MoveNew, the default, or MoveReplace.
(file-write-text "config.tmp" text)
(file-move "config.tmp" "config" #:mode MoveReplace)   ; never seen half-written

MoveNew fails if to exists. MoveReplace replaces a file at to, in the one rename that moves the new one there, so nothing ever sees to missing: write a temporary file, then move it over the old one. A directory is never replaced, and never replaces anything.

Through the FS effect’s fs-move; an Err from it is raised.

See also: MoveMode, file-copy, fs-move

file-read/seq

function ↑ Functions

(: file-read/seq (-> (-> InputPort %a) string (Seq %a)))
(file-read/seq reader path)

The items a reader reads from a file, pulled lazily.

reader
Reads one item from the port. Called while the port is not at its end.
path
The file to read.
returns
A sequence of the items, which may be walked more than once.

The file is opened when the sequence is walked, not when it is made, so every walk opens it afresh and reads from the start, using whatever FS handler is active when iterated. It is closed when the walk ends: at the end of the file; when a loop, find or any? walking it stops early, or the consumer of a lazy seql over it does (see iterable-end); and when an exception or a non-local exit leaves the loop (see iterable-cleanup). A walk that is never ended, such as an enumerator that .NET code takes and drops, leaves the file open until the enclosing scope ends: the port is registered with the scope that is ambient at the first pull. In main that is the end of the program, so put such a walk in a with-scope to close it sooner.

A missing file raises on the first pull. (std ports)’ file->seq, which is built on this, reports it as a Result at the call instead.

A seq body cannot await, so a bjoroutine pulling from this parks its thread on every pull. In a bjoroutine, read the whole file with file-read-lines, or stream it with port->chan.

See also: file-read-lines/seq, file-read-lines

file-read-lines/seq

function ↑ Functions

(: file-read-lines/seq (-> string (#:mode LineMode) (Seq string)))
(file-read-lines/seq path #:mode Any)

The lines of a file, pulled lazily.

path
The file to read.
#:mode
What ends a line, as for read-line: Any by default.
returns
A sequence of the lines, without their line ends.

file-read/seq with read-line: opened at each walk, closed when the walk ends, and never suspending.

See also: file-read/seq, file-read-lines, LineMode

path-absolute

function ↑ Functions

(: path-absolute (-> string string))
(path-absolute path)

A path made absolute, against the current directory.

path
The path, relative or absolute.
returns
The full path.

.NET’s Path.GetFullPath. Like the other path functions it works on the text and asks nothing of the file system.

See also: current-directory, path-combine

path-combine

function ↑ Functions

(: path-combine (-> #:rest string string))
(path-combine #:rest parts)

Paths joined with the separator.

parts ...
The pieces, in order.
returns
The joined path.
(path-combine "src" "std" "prelude.bjo")   ; "src/std/prelude.bjo" on Linux

.NET’s Path.Combine, so a piece that is itself an absolute path starts the result over from it.

See also: path-directory, path-filename, path-absolute

path-filename

function ↑ Functions

(: path-filename (-> string (Option string)))
(path-filename path)

The last part of a path: the file’s name and extension.

path
The path.
returns
None for a path that ends in a separator, which names a directory.
(path-filename "src/main.bjo")   ; (Some "main.bjo")
(path-filename "src/")           ; None

See also: path-file-extension, path-directory

path-file-extension

function ↑ Functions

(: path-file-extension (-> string (Option string)))
(path-file-extension path)

The extension of a path’s file name, with its dot.

path
The path.
returns
None when the name has no extension.
(path-file-extension "main.bjo")   ; (Some ".bjo")
(path-file-extension "Makefile")   ; None

A name that is nothing but a dotted suffix, .bashrc, counts as an extension, as it does to .NET.

See also: path-filename

path-directory

function ↑ Functions

(: path-directory (-> string (Option string)))

The directory part of a path: all of it but the last part.

path
The path.
returns
None for a root and for a bare file name.
(path-directory "src/main.bjo")   ; (Some "src")
(path-directory "main.bjo")       ; None

.NET’s Path.GetDirectoryName, mapping null and empty strings to None. A builtin rather than a function of the prelude’s own, for that reason.

See also: path-filename, path-combine

directory-exists?

function ↑ Functions

(: directory-exists? (-> string bool))
(directory-exists? path)

Whether a path names a directory.

path
The path to ask about.
returns
#t for a directory, #f for a file or for nothing.

See also: file-exists?, file-info

directory-create

function ↑ Functions

(: directory-create (-> string void))
(directory-create path)

Creates a directory, and every missing one along its path.

path
The directory to create.

One that is already there is not an error, so the call needs no guard. Through the FS effect’s fs-create-directory; an Err from it is raised.

See also: directory-delete, fs-create-directory

directory-delete

function ↑ Functions

(: directory-delete (-> string void))
(directory-delete path)

Deletes an empty directory.

path
The directory to delete. Empty.

A missing or non-empty directory is an error, raised from the FS effect’s fs-delete-directory.

See also: directory-delete-tree, file-delete, fs-delete-directory

directory-delete-tree

function ↑ Functions

(: directory-delete-tree (-> string void))
(directory-delete-tree path)

Deletes a directory and everything under it.

path
The directory to delete.

Spelled differently from directory-delete because it is not a mistake anything can undo.

It deletes one entry at a time through the FS operations, so a handler sees every deletion. A symbolic link to a directory is removed as a link and never entered, path itself included, so nothing a link points at is deleted: a link to the home directory inside a build directory leaves the home directory alone, and a link back up the tree does not loop. A link that leads nowhere is removed as a file.

See also: directory-delete, directory-walk

directory-files

function ↑ Functions

(: directory-files (-> string (Vec string)))
(directory-files path)

The files directly in a directory.

path
The directory to list.
returns
Whole paths, in the order the OS lists them.
(vec-filter #(string-ends-with? &1 ".bjo") (directory-files dir))

Directory listing does not accept a pattern glob; filter the returned vector instead. An error listing is raised from the FS effect’s fs-list.

See also: directory-subdirectories, directory-walk

directory-subdirectories

function ↑ Functions

(: directory-subdirectories (-> string (Vec string)))
(directory-subdirectories path)

The directories directly in a directory.

path
The directory to list.
returns
Whole paths, in the order the OS lists them.

See also: directory-files, directory-walk

directory-walk

function ↑ Functions

(: directory-walk (-> string (#:into? (-> string bool)) (Seq string)))
(directory-walk dir #:into? (fun (d) #t))

The files under a directory, depth first, pulled lazily.

dir
The directory to walk.
#:into?
Asked about each directory below dir before the walk enters it. By default every one is entered.
returns
A sequence of whole paths to files; directories themselves are not in it.
(filter #(string-ends-with? & ".bjo")
        (directory-walk "." #:into? (fun (d) (not (= (path-filename d) (Some ".git"))))))

(find #(string-ends-with? & ".bjo") (directory-walk "."))   ; stops at the first

Each directory’s entries come in ordinal order, so a walk is the same on every OS and on a fake filesystem. A directory that is a symbolic link is never entered, so a link back up the tree cannot loop the walk. An entry gone between listing and visiting is skipped.

Nothing is listed until the sequence is walked, using whatever FS handler is active during traversal. Stopping early avoids reading further entries. An error listing a directory is raised, as directory-files raises it. A seq body cannot await, so a bjoroutine pulling from it parks its thread on each pull.

See also: directory-files, directory-delete-tree

fs-info

function ↑ Functions

(: fs-info (-> string (Option FsInfo)))

The FS operation that queries metadata for a path.

path
The path to ask about.
returns
None when the path names nothing.

An operation of the FS effect: it calls the handler installed for it, fs-info/raw when none is. Install one with (with-handler ((fs-info (fun (path) ...))) body ...), which needs (import (std effect)). file-info, file-exists?, directory-exists? and the directory functions ask through it.

See also: file-info, FsInfo, op/fs-info, fs-info/raw

fs-info/raw

function ↑ Functions

(: fs-info/raw (-> string (Option FsInfo)))
(fs-info/raw path)

What the real file system says a path names, bypassing any FS handler.

path
The path to ask about.
returns
None when the path names nothing, or is no path at all.

The default handler of fs-info, and what a handler that wants to fall through to the disk calls. A symbolic link’s size and time are those of the end of its chain of links, followed for at most 40 steps; a link to nothing keeps its own.

See also: fs-info, FsInfo

fs-list

function ↑ Functions

(: fs-list (-> string (Result Exception (Vec string))))

The FS operation that lists a directory.

dir
The directory to list.
returns
Whole paths, files and directories both, or the error listing it.

An operation of the FS effect: it calls the handler installed for it, fs-list/raw when none is. directory-files, directory-subdirectories, directory-walk and directory-delete-tree list through it.

See also: directory-files, directory-walk, op/fs-list, fs-list/raw

fs-list/raw

function ↑ Functions

(: fs-list/raw (-> string (Result Exception (Vec string))))
(fs-list/raw path)

The entries of a directory on the real file system, bypassing any FS handler.

path
The directory to list.
returns
Whole paths, in the order the OS gives them, or the exception .NET raised.

See also: fs-list

fs-create-directory

function ↑ Functions

(: fs-create-directory (-> string (Result Exception Unit)))

The FS operation that creates a directory and every missing one along its path.

dir
The directory to create.
returns
Ok when it is there afterwards, or the error.

An operation of the FS effect: it calls the handler installed for it, fs-create-directory/raw when none is.

See also: directory-create, op/fs-create-directory, fs-create-directory/raw

fs-create-directory/raw

function ↑ Functions

(: fs-create-directory/raw (-> string (Result Exception Unit)))
(fs-create-directory/raw path)

Creates a directory on the real file system, bypassing any FS handler.

path
The directory to create.
returns
Ok, or the exception .NET raised.

Every missing directory along the path is created, and one that is already there is not an error.

See also: fs-create-directory

fs-delete-file

function ↑ Functions

(: fs-delete-file (-> string (Result Exception Unit)))

The FS operation that deletes a file.

path
The file to delete.
returns
Ok, or the error.

An operation of the FS effect: it calls the handler installed for it, fs-delete-file/raw when none is.

See also: file-delete, op/fs-delete-file, fs-delete-file/raw

fs-delete-file/raw

function ↑ Functions

(: fs-delete-file/raw (-> string (Result Exception Unit)))
(fs-delete-file/raw path)

Deletes a file on the real file system, bypassing any FS handler.

path
The file to delete.
returns
Ok, also when the file is missing, or the exception .NET raised.

See also: fs-delete-file

fs-delete-directory

function ↑ Functions

(: fs-delete-directory (-> string (Result Exception Unit)))

The FS operation that deletes an empty directory.

dir
The directory to delete.
returns
Ok, or the error.

An operation of the FS effect: it calls the handler installed for it, fs-delete-directory/raw when none is.

See also: directory-delete, op/fs-delete-directory, fs-delete-directory/raw

fs-delete-directory/raw

function ↑ Functions

(: fs-delete-directory/raw (-> string (Result Exception Unit)))
(fs-delete-directory/raw path)

Deletes an empty directory on the real file system, bypassing any FS handler.

path
The directory to delete.
returns
Ok, or the exception .NET raised: a missing or non-empty directory is an IOException.

See also: fs-delete-directory

fs-move

function ↑ Functions

(: fs-move (-> string string MoveMode (Result Exception Unit)))

The FS operation that moves or renames a file or a directory.

from
What to move.
to
Its new path.
mode
What to do when something is already there.
returns
Ok, or the error.

An operation of the FS effect: it calls the handler installed for it, fs-move/raw when none is. file-move moves through it, and file-copy with Truncate replaces its target with it.

See also: file-move, MoveMode, op/fs-move, fs-move/raw

fs-move/raw

function ↑ Functions

(: fs-move/raw (-> string string MoveMode (Result Exception Unit)))
(fs-move/raw from to mode)

Moves a file or a directory on the real file system, bypassing any FS handler.

from
What to move.
to
Its new path.
mode
Whether a file at to is replaced. Ignored for a directory, which never replaces.
returns
Ok, or the exception .NET raised.

See also: fs-move, MoveMode

get-environment-variable

function ↑ Functions

(: get-environment-variable (-> string (Option string)))
(get-environment-variable name)

The value of an environment variable of this process.

name
The variable's name.
returns
None when it is not set, or set to the empty string.

Follows R7RS naming, returning None where R7RS returns #f. What it cannot tell apart is a variable that is unset and one set to nothing. It reads the real environment directly; getenv asks through a handler a test can replace.

See also: set-environment-variable!, getenv

set-environment-variable!

function ↑ Functions

(: set-environment-variable! (-> string string void))
(set-environment-variable! name value)

Sets an environment variable for this process and the processes it starts.

name
The variable's name.
value
Its new value. The empty string removes it.

Not for the shell that started the process.

See also: get-environment-variable

current-directory

function ↑ Functions

(: current-directory (-> string))
(current-directory)

The process’s current directory, which relative paths are resolved against.

returns
Its full path.

A function rather than a value, because it is process-wide mutable state.

See also: set-current-directory!, path-absolute

set-current-directory!

function ↑ Functions

(: set-current-directory! (-> string void))
(set-current-directory! path)

Changes the process’s current directory.

path
The new current directory.

Process-wide: every thread and fiber resolves relative paths against it from then on.

See also: current-directory

getenv

function ↑ Functions

(: getenv (-> string (Option string)))

The Env operation that reads an environment variable.

name
The variable's name.
returns
None when it is not set.
(with-handler ((getenv (fun (name) (if (= name "HOME") (Some "/tmp/home") None))))
  (run-the-thing))

An operation of the Env effect, allowing tests to mock environment variables without modifying the process environment. With no handler installed it is get-environment-variable. Installing one needs (import (std effect)).

See also: get-environment-variable, op/getenv

display

function ↑ Functions

(: display (-> string void))

Writes a string to the current output port.

s
The text, written as it is, with no newline after it.

Writes to whatever current-output-port is bound to. It takes a string; print takes any value, through displayed.

See also: displayln, newline, print, current-output-port, write-string

displayln

function ↑ Functions

(: displayln (-> string void))

Writes a string and a newline to the current output port.

s
The text, followed by the port's line terminator.

See also: display, newline, println, writeln

newline

function ↑ Functions

(: newline (-> void))

Writes a newline to the current output port.

The port’s line terminator, which for standard output is the platform’s.

See also: displayln, current-output-port

open-input-file

function ↑ Functions

(: open-input-file (-> string (Result Exception InputPort)))
(open-input-file path)

Opens a file for reading.

path
The file.
returns
The port, or Err with the .NET exception when the file cannot be opened.
(match (open-input-file "notes.txt")
  ((Ok p) (read-all p))
  ((Err (:is System.IO.FileNotFoundException)) "")
  ((Err e) (raise e)))

A missing file is expected, so it is a Result rather than a raise. The Err carries the real exception, so an arm can test for System.IO.FileNotFoundException.

The file is opened through the open-read-stream operation, so a handler of the FS effect intercepts it. The port is owned by the ambient scope: when the scope returns, the file is closed, whether the program closed it or not. The scope is read before the file is opened, so a program with no scope fails without having opened anything.

The port’s text reads decode UTF-8; see InputPort for invalid bytes, and for reading a file in another encoding.

See also: call-with-input-file, open-input-file/raw, open-read-stream, close-input-port, read-all

open-input-file/raw

function ↑ Functions

(: open-input-file/raw (-> string (Result Exception InputPort)))
(open-input-file/raw path)

Opens a file for reading, past any FS handler.

path
The file.
returns
The port, or Err with the .NET exception.

open-input-file over open-read-stream/raw: the real filesystem whatever handler is installed. What a fake filesystem calls to fall through to the disk. The port is owned by the ambient scope.

See also: open-input-file, open-read-stream/raw

open-output-file

function ↑ Functions

(: open-output-file (-> string (#:mode WriteMode) (Result Exception OutputPort)))
(open-output-file path #:mode Truncate)

Opens a file for writing.

path
The file.
#:mode
How: Truncate, the default, Append or CreateNew.
returns
The port, or Err with the .NET exception when the file cannot be opened.
(open-output-file "log.txt" #:mode Append)

The file is opened through the open-write-stream operation, so a handler of the FS effect intercepts it. The port is owned by the ambient scope and closed when the scope returns.

What is written is buffered. Closing flushes, but synchronously: flush-port before the close lets a bjoroutine suspend on the write instead.

See also: call-with-output-file, WriteMode, open-output-file/raw, open-write-stream, close-output-port

open-output-file/raw

function ↑ Functions

(: open-output-file/raw (-> string WriteMode (Result Exception OutputPort)))
(open-output-file/raw path mode)

Opens a file for writing, past any FS handler.

path
The file.
mode
Truncate, Append or CreateNew.
returns
The port, or Err with the .NET exception.

open-output-file over open-write-stream/raw: the real filesystem whatever handler is installed. The mode is positional here. The port is owned by the ambient scope.

See also: open-output-file, open-write-stream/raw, WriteMode

open-input-string

function ↑ Functions

(: open-input-string (-> string InputPort))
(open-input-string contents)

A string as an input port.

contents
The text the port reads.
returns
The port. It cannot fail, so there is no Result.
(read-line (open-input-string "one\ntwo"))   ; "one"

Memory only, so no scope owns it. Its reads never suspend, in either colour.

See also: open-output-string, open-input-file

open-output-string

function ↑ Functions

(: open-output-string (-> OutputPort))
(open-output-string)

A port that collects what is written to it.

returns
The output port. Call get-output-string to retrieve accumulated text.

Memory only, so no scope owns it. To build a string, prefer a StringBuilder: writing to a port carries a colour, so a function that writes to one gets a suspending copy, where a builder keeps it an ordinary function.

See also: get-output-string, open-input-string

get-output-string

function ↑ Functions

(: get-output-string (-> OutputPort string))
(get-output-string p)

Everything written to a string port so far.

p
A port from open-output-string.
returns
The text collected. The port stays open and keeps collecting.
raises System.InvalidOperationException
When p is not a port from open-output-string.
(def out (open-output-string))
(write-string out "a")
(get-output-string out)   ; "a"
(write-string out "b")
(get-output-string out)   ; "ab"

Bytes written with write-bytes! that are not UTF-8 read as U+FFFD, as Racket’s get-output-string reads them; get-output-bytes has them as they are.

See also: open-output-string, writer->string

get-output-bytes

function ↑ Functions

(: get-output-bytes (-> OutputPort (Array byte)))
(get-output-bytes p)

Everything written to a string port so far, as bytes.

p
A port from open-output-string.
returns
A copy of the bytes collected: text as UTF-8, and bytes as they were written.
raises System.InvalidOperationException
When p is not a port from open-output-string.
(def out (open-output-string))
(write-string out "å")
(get-output-bytes out)   ; #[195 165]

See also: get-output-string, open-output-string

close-input-port

function ↑ Functions

(: close-input-port (-> InputPort void))
(close-input-port p)

Closes an input port.

p
The port.

Rarely needed: with-open closes a port however the body ends, and the scope that owns a file port closes it when it returns.

A port a scope owns is released through its registration, so the scope’s list does not keep a spent entry. A port nothing owns, such as a string port, is disposed. Standard input is never closed.

See also: close-output-port, call-with-input-file

close-output-port

function ↑ Functions

(: close-output-port (-> OutputPort void))
(close-output-port p)

Flushes and closes an output port.

p
The port.

Rarely needed: with-open closes a port however the body ends, and the scope that owns a file port closes it when it returns.

A port a scope owns is released through its registration, and its buffered text is written before the file is closed. That flush is synchronous; call flush-port first for one a bjoroutine suspends on. A port nothing owns is disposed. On standard output or standard error it flushes and stops: nothing can take them away from the rest of the program.

See also: close-input-port, flush-port, call-with-output-file

call-with-input-file

function ↑ Functions

(: call-with-input-file (-> string (-?-> InputPort %a) (Result Exception %a)))
(call-with-input-file path proc)

Opens a file, hands the port to a function, and closes it.

path
The file.
proc
What to do with the port. Either colour.
returns
Ok containing proc's return value, or Err when the file cannot be opened.
(call-with-input-file "notes.txt" read-all)

The port is closed however proc ends, through its registration, so the scope’s list is back to the length it had. An exception from proc is raised, not put in the Err.

See also: open-input-file, call-with-output-file

call-with-output-file

function ↑ Functions

(: call-with-output-file (-> string (-?-> OutputPort %a) (#:mode WriteMode) (Result Exception %a)))
(call-with-output-file path proc #:mode Truncate)

Opens a file for writing, hands the port to a function, and closes it.

path
The file.
proc
What to do with the port. Either colour.
#:mode
How the file is opened, as for open-output-file: Truncate by default.
returns
Ok containing proc's return value, or Err when the file cannot be opened.
(call-with-output-file "out.txt"
  (fun (p) (writeln p "hello")))

The port is closed however proc ends, which writes what is still buffered. An exception from proc is raised, not put in the Err.

See also: open-output-file, call-with-input-file, WriteMode

port-eof?

function ↑ Functions

(: port-eof? (-> InputPort bool))
(port-eof? p)

Whether a port has no more input.

p
The port.
returns
#t at end of input. Asking consumes nothing.

On a file port, or standard input, it checks the buffer directly whenever the buffer holds anything, and reads ahead only when it is empty. That read suspends in a bjoroutine.

See also: read-line, read-line/opt, read-char/opt

read-line

function ↑ Functions

(: read-line (-> InputPort (#:mode LineMode) string))
(read-line p #:mode Any)

The next line of a port, without its line terminator.

p
The port. Not at end of input.
#:mode
What ends a line: Any, the default, AnyOne, Linefeed, Return or ReturnLinefeed.
returns
The line. A line at the end of input needs no terminator.
raises System.IO.EndOfStreamException
When the port is at end of input.
(let loop ()
  (unless (port-eof? p)
    (displayln (read-line p))
    (loop)))

(read-line p #:mode Linefeed)   ; a \\r stays in the line

The keyword makes read-line a function of two arguments where it is passed as a value, so a reader that takes one is handed (fun (p) (read-line p)).

See also: read-line/opt, LineMode, port-eof?, read-all, in-port

read-line/opt

function ↑ Functions

(: read-line/opt (-> InputPort (#:mode LineMode) (Option string)))
(read-line/opt p #:mode Any)

The next line of a port, or None at end of input.

p
The port.
#:mode
What ends a line, as for read-line: Any by default.
returns
Some line without its terminator, or None at end of input.
(when-let (line (read-line/opt port))
  (displayln line))

One read. Where two fibers share a port, this is the way to read it to the end: port-eof? followed by read-line is two, and the other fiber can take the last line between them.

Passed as a value, it is (fun (p) (read-line/opt p)), for the reason read-line is.

See also: read-line, LineMode, in-port, port-fold

read-char

function ↑ Functions

(: read-char (-> InputPort char))
(read-char p)

The next character of a port.

p
The port. Not at end of input.
returns
The character: a Unicode scalar, so one outside the BMP is one char.
raises System.IO.EndOfStreamException
When the port is at end of input.
raises System.InvalidOperationException
When a .NET caller's UTF-16 read has left half a character behind.

Decodes one character of UTF-8 from the port’s bytes, however many bytes it takes, so reading a port a character at a time agrees with read-all walked as a string. An invalid sequence reads as U+FFFD.

The InvalidOperationException can only follow a .NET API’s own reads of the port as a TextReader, which hand out a character above the BMP as two UTF-16 units: after the first of them, the next read is half a character.

See also: read-char/opt, write-char, port-eof?

read-char/opt

function ↑ Functions

(: read-char/opt (-> InputPort (Option char)))
(read-char/opt p)

The next character of a port, or None at end of input.

p
The port.
returns
Some character, or None at end of input.
raises System.InvalidOperationException
When the port holds a surrogate that is not half of a pair.

One read, for the reason read-line/opt is. A character outside the BMP is taken whole, so two fibers reading one port never split it.

See also: read-char, in-port

peek-char

function ↑ Functions

(: peek-char (-> InputPort char))
(peek-char p)

The next character of a port, left in the port.

p
The port. Not at end of input.
returns
The character read-char would answer.
raises System.IO.EndOfStreamException
When the port is at end of input.
raises System.InvalidOperationException
When a .NET caller's UTF-16 read has left half a character behind.
(def p (open-input-string "ab"))
(peek-char p)   ; #\\a
(read-char p)   ; #\\a
(peek-char p)   ; #\\b

As Racket’s peek-char. Decoded from the port’s buffer like read-char, waiting for as many bytes as the character needs, and taking none of them: the next read, of characters or of bytes, starts at the same place. An invalid sequence peeks as U+FFFD.

A peek and the read after it are two operations: another fiber reading the same port can take the character between them.

See also: peek-char/opt, read-char

peek-char/opt

function ↑ Functions

(: peek-char/opt (-> InputPort (Option char)))
(peek-char/opt p)

The next character of a port, left in the port, or None at end of input.

p
The port.
returns
Some character, or None at end of input.
raises System.InvalidOperationException
When the port holds a surrogate that is not half of a pair.

See also: peek-char, read-char/opt

read-all

function ↑ Functions

(: read-all (-> InputPort string))
(read-all p)

Everything left in a port, as one string.

p
The port.
returns
The rest of the input. Empty at end of input.

See also: read-line, port-fold

port-fold

function ↑ Functions

(: port-fold (-> (-?-> InputPort %a %a) %a InputPort %a))
(port-fold f init port)

Folds a reading function over a port until it is out.

f
Called with (port, acc) while there is input; reads from port and returns the new accumulator value. Either colour.
init
The first accumulator.
port
The port.
returns
The accumulator once the port is at end of input.
(port-fold (fun (p n) (ignore (read-line p)) (+ n 1)) 0 port)   ; lines left

f is called only when port-eof? says there is more, and decides how much one step reads. A suspending f makes the fold suspend, so it is the way to read a port element by element in a bjoroutine.

See also: in-port, read-line, port-eof?

in-port

function ↑ Functions

(: in-port (-> InputPort (-> InputPort (Option %a)) (PortReads %a)))
(in-port port read)

A port as something a loop walks, read by a function of your choice.

port
The port.
read
Reader function returning (Some element), or None at end of input.
returns
A PortReads, which is Iterable.
(loop (:for line (in-port p (fun (q) (read-line/opt q))))
      (:do (displayln line)))

read-line/opt and read-char/opt are the two readers the prelude has; any (-> InputPort (Option %a)) will do.

The walk reads one ahead, because it has to know it is done before the element is asked for: a loop left by :finish has consumed the element it did not look at.

It blocks. Iterable’s methods are synchronous, so the reader’s synchronous copy runs even inside a bjoroutine. A walk that should suspend wants port-fold.

See also: PortReads, read-line/opt, read-char/opt, port-fold

write-string

function ↑ Functions

(: write-string (-> OutputPort string void))
(write-string p s)

Writes a string to a port.

p
The port.
s
The text, written as it is.

The port comes first, as for every port operation. A file port buffers the text, so it reaches the file at a flush, a close, or when the buffer fills; in a bjoroutine a write that fills the buffer suspends on the drain.

See also: writeln, write-char, flush-port, display

writeln

function ↑ Functions

(: writeln (-> OutputPort string void))
(writeln p s)

Writes a string and a newline to a port.

p
The port.
s
The text, followed by the port's line terminator.

See also: write-string, displayln

write-char

function ↑ Functions

(: write-char (-> OutputPort char void))
(write-char p c)

Writes one character to a port.

p
The port.
c
The character. One outside the BMP is written as both of its UTF-16 units.

See also: read-char, write-string

flush-port

function ↑ Functions

(: flush-port (-> OutputPort void))
(flush-port p)

Writes what a port has buffered to where it goes.

p
The port.

In a bjoroutine it suspends on the write. Closing a port flushes too, but synchronously, so flush first where waiting should not block a thread.

See also: close-output-port, write-string

reader-read-line!

function ↑ Functions

(: reader-read-line! (-> Bjolang.Runtime.BjoInputPort string))

The next line of a reader, blocking until it is read.

r
The reader. Not at end of input.
returns
The line, without its line terminator.
raises System.IO.EndOfStreamException
When the reader is at end of input.

A runtime primitive that only blocks; it has no suspending copy. read-line is the same read in both colours, and is what a program calls.

See also: read-line, read-line/opt

reader-read-char!

function ↑ Functions

(: reader-read-char! (-> Bjolang.Runtime.BjoInputPort char))

The next character of a reader, blocking until it is read.

r
The reader. Not at end of input.
returns
The character, with a surrogate pair put back together.
raises System.IO.EndOfStreamException
When the reader is at end of input.
raises System.InvalidOperationException
When the reader holds a surrogate that is not half of a pair.

A runtime primitive that only blocks; it has no suspending copy. read-char is the same read in both colours, and is what a program calls.

See also: read-char, read-char/opt

writer-write-char!

function ↑ Functions

(: writer-write-char! (-> Bjolang.Runtime.BjoOutputPort char void))

Writes one character to a writer.

w
The writer.
c
The character. One outside the BMP is written as both of its UTF-16 units.

A runtime primitive with no suspending copy. write-char is the same write in both colours, and is what a program calls.

See also: write-char

writer->string

function ↑ Functions

(: writer->string (-> Bjolang.Runtime.BjoOutputPort string))

What a string writer has collected.

w
A writer from open-output-string.
returns
The text written to it so far.
raises System.InvalidOperationException
When w is not a string writer.

What get-output-string is built on. It raises rather than returning the writer’s type name, which is what .NET’s ToString would give for a file port.

See also: get-output-string

open-read-stream

function ↑ Functions

(: open-read-stream (-> string (Result Exception Stream)))

Opens a file as a stream for reading: an operation of the FS effect.

path
The path.
returns
The stream, or Err with the exception.

Everything in the prelude and (std ports) that reads a file opens it through this, so a handler installed with with-handler intercepts all reads: a test reads from a fake, a sandbox refuses. With no handler it falls back to open-read-stream/raw.

Returns a Stream, not a port. open-input-file builds the port over it and registers it on the ambient scope, so a MemoryStream a handler made is owned exactly as a file is.

See also: open-read-stream/raw, op/open-read-stream, open-input-file, open-write-stream

open-write-stream

function ↑ Functions

(: open-write-stream (-> string WriteMode (Result Exception Stream)))

Opens a file as a stream for writing: an operation of the FS effect.

path
The path.
mode
How the file is opened.
returns
The stream, or Err with the exception.

Everything in the prelude and (std ports) that writes a file opens it through this, so an installed handler intercepts all writes. With no handler it falls back to open-write-stream/raw.

Returns a Stream, not a port. open-output-file builds the port over it and registers it on the ambient scope.

See also: open-write-stream/raw, op/open-write-stream, open-output-file, WriteMode

open-read-stream/raw

function ↑ Functions

(: open-read-stream/raw (-> string (Result Exception Stream)))
(open-read-stream/raw path)

Opens a file on disk as a stream for reading, past any handler.

path
The file.
returns
The stream, or Err with an IOException or UnauthorizedAccessException.

The default handler of open-read-stream. Read-only, with other readers allowed alongside. A missing file is a FileNotFoundException, which is an IOException.

See also: open-read-stream, open-input-file/raw

open-write-stream/raw

function ↑ Functions

(: open-write-stream/raw (-> string WriteMode (Result Exception Stream)))
(open-write-stream/raw path mode)

Opens a file on disk as a stream for writing, past any handler.

path
The file.
mode
Truncate, Append or CreateNew.
returns
The stream, or Err with an IOException or UnauthorizedAccessException.

The default handler of open-write-stream. Write-only, with readers allowed alongside. CreateNew on a file that exists is an IOException.

See also: open-write-stream, open-output-file/raw, WriteMode

warn

function ↑ Functions

(: warn (-> string void))

Reports that something is wrong, and carries on: an operation of the Diagnostics effect.

message
The message.
(warn "config.toml not found; using defaults")

By default it writes the message as a line on current-error-port. A handler installed with with-handler decides otherwise: collect the warnings, count them, or raise to make them fatal.

It is synchronous on purpose, so that an ordinary function can warn. A handler that wants to hand the line to a channel puts it on a mutable queue rather than syncing.

See also: log, op/warn, current-error-port

log

function ↑ Functions

(: log (-> string void))

A line of diagnostics: an operation of the Diagnostics effect.

message
The line.
(with-handler ((log (let ((outer (handler-of log)))
                      (fun (s) (outer (str "[app] " s))))))
  (log "started"))

By default it writes the line on current-error-port. A handler installed with with-handler sends it elsewhere. A handler that calls log calls itself; (handler-of log) is the one installed before it.

Synchronous, like warn, so an ordinary function can log. The natural logarithm is loge, in (std maths).

See also: warn, op/log, current-error-port

sync

function ↑ Functions

(: sync (-bjo-> (Event %a) %a))

Synchronizes on an event and returns its value: the yield point of a bjoroutine.

ev
The event to wait for. Any event: a channel operation, a choose, a timeout, a promise's join.
returns
The value of the event that committed.
raises Bjolang.Runtime.Cancelled
When the ambient token fires before the event commits.
(sync (chan-recv jobs))
(sync (choose (chan-recv a) (chan-recv b)))

Building an event never suspends; only sync does, so only a bjoroutine may write it. The other yield points are calls to bjoroutines (chan-put, chan-get, the scope forms, an #:async .NET call), and a fiber may resume on a different thread after any of them. Other fibers run on other threads at the same time: nothing gives a fiber exclusive access to state it shares with another, even between two syncs, so shared state is passed on a channel or guarded, as it would be between threads.

Every sync watches the ambient token, current-cancel: once the scope it runs in has been cancelled, the sync raises instead of waiting. An event that is ready at the sync still commits, since the token is offered after the event’s own branches and a cancellation never undoes a commit. Code that has to wait after a cancellation, such as cleanup, runs inside with-shield.

A plain defun cannot write it. sync/blocking is the same wait for an ordinary function, parking the calling thread.

See also: sync/blocking, choose, chan-get, chan-put, current-cancel

sync/blocking

function ↑ Functions

(: sync/blocking (-> (Event %a) %a))

Waits for an event from an ordinary function, parking the calling thread.

ev
The event to wait for.
returns
The value of the event that committed.
raises Bjolang.Runtime.Cancelled
When the ambient token fires first, raised on the calling thread.
(sync/blocking (chan-recv ch))
(sync/blocking (promise-join (bjo (work 21))))
(sync/blocking (choose (wrap (chan-recv ch) (fun (v) (Got v)))
                       (wrap (timeout (seconds 1)) (fun (u) TimedOut))))

No fiber is spawned. It is the mirror of blocking: that one carries a thread-parking call into fiber-land, this one carries an event out.

Do not call it from inside a bjoroutine. It parks the thread it is called on, and inside a fiber that thread belongs to the pool, which is what the events being waited for need in order to fire. Use sync instead.

Nothing withdraws it once parked. A wait that might not end needs its own way out composed in first, as with the timeout above. The ambient token is offered as one more branch, as sync offers it.

See also: sync, blocking, promise-join/sync

make-chan

function ↑ Functions

(: make-chan (-> (Chan %a)))

A new synchronous, unbuffered channel.

returns
A channel on which a send and a receive meet.

A rendezvous: neither a send nor a receive completes until the other arrives, which is where backpressure comes from.

A channel has no close. A producer that has to say it is finished hands over a promise beside the channel, as async-seq->chan does.

Waiting operations on a contended channel are not guaranteed to be served in the order they arrived.

See also: chan-send, chan-recv, chan-put, chan-get

chan-send

function ↑ Functions

(: chan-send (-> (Chan %a) %a (Event void)))

The event of handing a value over a channel.

ch
The channel.
v
The value to hand over.
returns
An event that commits when a receiver takes v.

Not the handing over: that happens at the sync. Building the event does nothing to the channel, and a send that loses a choose is withdrawn, so v is never delivered.

(sync (chan-send ch v)) is (chan-put ch v), which builds no event value. The compiler emits it as chan-put when it is written that way. A send event that gets to sync in another way, for example in a variable, is built.

See also: chan-put, chan-recv, sync, choose

chan-recv

function ↑ Functions

(: chan-recv (-> (Chan %a) (Event %a)))

The event of taking one message off a channel.

ch
The channel.
returns
An event whose value is the message taken.

A receive that loses a choose is removed from the channel, so nothing is left waiting for a message that will never be read.

(sync (chan-recv ch)) is (chan-get ch).

See also: chan-get, chan-send, sync, choose

chan-put

function ↑ Functions

(: chan-put (-bjo-> (Chan %a) %a void))

Hands a value over a channel, and returns when it has been taken.

ch
The channel.
v
The value to hand over.
raises Bjolang.Runtime.Cancelled
When the ambient token fires before a receiver takes v.

(sync (chan-send ch v)) without the event value in between, as in Guile’s put-message beside its put-operation. It waits and is cancelled exactly as sync is. The event form is for what an event is for: choose, wrap, and passing one around.

See also: chan-send, chan-get, sync

chan-get

function ↑ Functions

(: chan-get (-bjo-> (Chan %a) %a))

Takes one message off a channel, waiting for a sender.

ch
The channel.
returns
The message.
raises Bjolang.Runtime.Cancelled
When the ambient token fires before a sender arrives.

(sync (chan-recv ch)) in one call. It waits and is cancelled exactly as sync is.

See also: chan-recv, chan-put, sync

async-seq->chan

function ↑ Functions

(: async-seq->chan (-> (AsyncSeq %a) (Tuple (Chan %a) (Promise void))))

A .NET async stream as a channel, and a promise that it is over.

s
The stream, an IAsyncEnumerable.
returns
A tuple of the channel the items arrive on and a promise that lands when the stream has ended or failed.

An async stream can only be walked. A channel can go into a choose, be raced against a timeout and be withdrawn, so a fiber pumps the one into the other. The pump belongs to the scope that asked for the stream as a spawn/daemon does: the scope does not wait for it, and when the scope ends the pump stops, even in the middle of a send nobody takes, and the promise fails with Cancelled.

The channel is synchronous, so the pump waits in the rendezvous until a receiver takes each item: a slow consumer stops the producer rather than growing a buffer. For the same reason the pump cannot finish until its last item was taken, so when the promise lands the channel is empty, and a consumer choosing between the two branches never has to guess.

The promise is there because a channel has no close, and a close could not say why the stream ended. A stream that throws fails the promise.

A stream that stalls while producing an item stalls the pump with it: the token is the stream’s to honour.

See also: make-chan, promise-join, choose

choose

function ↑ Functions

(: choose (-> (Array (Event %a)) (Event %a)))

An event that offers several and commits to exactly one.

evs ...
The events to offer.
returns
An event whose value is the value of whichever event committed.
(sync (choose (wrap (chan-recv results) #(Some &))
              (wrap (timeout (milliseconds 20)) (fun (u) None))))

The losers are withdrawn, not merely ignored: a losing receive is taken off its channel and a losing send never delivers.

Order is priority. When several branches are ready at the sync, the first one written wins, every time. A loop that chooses between two busy channels can therefore starve the second.

An event that is always ready, such as always, a promise that has landed or a token that has fired, wins every iteration of a loop it is offered in.

See also: wrap, guard, with-nack, sync, never

wrap

function ↑ Functions

(: wrap (-> (Event %a) (-> %a %b) (Event %b)))

An event that applies a function to another event’s value upon commit.

ev
The event.
f
What to apply to its value once it has committed.
returns
An event that commits when ev commits, yielding (f value).
(choose (wrap (chan-recv ch) (fun (v) (Got v)))
        (wrap (timeout (seconds 1)) (fun (u) TimedOut)))

map for events, and the way branches of different types are brought to one type for a choose. f runs after the commit, as the value is delivered, so it does not decide whether its branch wins.

It runs on the fiber that synced, before sync returns, so it sees that fiber’s parameterize bindings and handlers, and what it raises is raised by the sync. The partner of a rendezvous has already gone on by then, and the value is consumed whether f returns or raises.

There is no bind: a composite with two commit points could not be withdrawn.

See also: choose, guard

guard

function ↑ Functions

(: guard (-> (-> (Event %a)) (Event %a)))

An event built afresh at each sync.

thunk
Makes the event, called each time the guard is synced.
returns
The event constructed by thunk at synchronization time.

For an event that depends on the moment of synchronisation, or that has to acquire something only when it is actually offered. thunk runs when the sync publishes the event, not when the guard is built.

See also: timeout, with-nack, choose

with-nack

function ↑ Functions

(: with-nack (-> (-> (Event void) (Event %a)) (Event %a)))

An event built with a second event that fires if it loses.

f
Function receiving the nack event and returning the event to synchronize.
returns
An event that is the branch f built, built afresh at each sync.

For a branch that acquires something which must be released if it does not win: a timer, a cancellation source, a tentative reservation. Without it, every losing choose leaks whatever the branch took.

The nack is a fact rather than a message: every listener sees it, and a late listener still does.

What reacts to the nack must not be ordinary work. Its callbacks run on a borrowed thread; they may wake a fiber or fire a token, as make-cancel’s thunk does, and nothing more.

See also: guard, choose

always

function ↑ Functions

(: always (-> %a (Event %a)))

An event that is always ready, with the given value.

v
Its value.
returns
An event that commits at once with v.

Always ready, so it wins every iteration of a choose loop it is offered in. That is the definition, and the same trap a landed promise sets.

See also: never, choose

never

function ↑ Functions

(: never (-> (Event %a)))

An event that is never ready.

returns
An event that never commits.

The identity of choose, and what a branch returns when it has nothing to offer. Synced on its own, only the ambient token firing ends the wait.

See also: always, choose

timeout

function ↑ Functions

(: timeout (-> Duration (Event Unit)))
(timeout d)

An event that is ready a length of time after it is synced.

d
A Duration, counted from each sync. Zero or less is ready at once.
returns
An event that commits with unit when the time is up.
(sync (choose (wrap (chan-recv ch) #(Some &))
              (wrap (timeout (seconds 5)) (fun (u) None))))

Relative to the sync, not to when the event was built, so one timeout value offered in a loop gives each iteration the full interval. A losing timeout’s timer is disposed.

For a budget over a whole loop, use at-time from (std datetime), which is ready at an Instant.

See also: seconds, choose, with-deadline

promise-join

function ↑ Functions

(: promise-join (-> (Promise %a) (Event (Result System.Exception %a))))

The event of a promise landing, with its success or failure.

p
The promise, from bjo or spawn-thunk.
returns
An event whose value is (Ok v), or (Err e) when the fiber raised e.
(match (sync (promise-join (bjo (fetch url))))
  ((Ok page) (use page))
  ((Err e) (log-failure e)))

Building the event does not wait; (sync (promise-join p)) does. Failure is a value because “the fiber died” is a fact the joiner needs.

A promise is persistent: once it has landed, every sync of its join commits immediately with the same value. A landed promise in a choose loop wins every iteration.

See also: promise-join/sync, promise-done?, detach

promise-join/sync

function ↑ Functions

(: promise-join/sync (-> (Promise %a) %a))
(promise-join/sync p)

Waits synchronously for a promise and returns its value.

p
The promise.
returns
The promise's value. When the fiber raised, that exception is raised here.
raises Bjolang.Runtime.Cancelled
When the ambient token fires before the promise lands, as for sync/blocking.

(sync/blocking (promise-join p)), with any failure re-raised rather than returned as an Err. It parks the calling thread, so it is for ordinary functions; a bjoroutine syncs on promise-join.

See also: promise-join, sync/blocking

promise-done?

function ↑ Functions

(: promise-done? (-> (Promise %a) bool))

Polls whether a promise has completed, without blocking.

p
The promise.
returns
#t once the promise has a value or a failure.

See also: promise-join

detach

function ↑ Functions

(: detach (-> (Promise %a) void))

Stops listening to a promise, deliberately.

p
The promise whose result is not wanted.

Dropping a promise loses any exception inside it silently. This says “I know, and I still do not want the result”, and a failure is reported to the scheduler’s unhandled-exception hook instead. A fiber that stopped because it was cancelled is not reported: that is how a worker normally ends.

(ignore p) on a promise is this.

See also: promise-join, spawn-thunk

spawn-thunk

function ↑ Functions

(: spawn-thunk (-> (-> %a) (Promise %a)))

Starts a thunk as a fiber of the current scope: bjo as a function.

f
The work. It runs to completion without suspending.
returns
A promise for the thunk's completion, identical to bjo.
raises Bjolang.Runtime.ScopeEnded
When there is no ambient scope.
(map spawn-thunk thunks)

bjo is a special form and not a value, so this is the spelling for the higher-order case. The fiber goes into the current scope as bjo’s does, and the scope waits for it.

A thunk has no yield point, so it cannot be cancelled: the scope waits for it to finish, and a long one holds its scope open. Spawned into a scope that has begun closing, it starts nothing and returns a promise that has already failed with Cancelled.

See also: detach, promise-join, spawn/thread

blocking

function ↑ Functions

(: blocking (-> (-> %a) (Event (Result System.Exception %a))))

An event that runs a thread-parking thunk off the fiber pool.

thunk
The work: a call that parks its thread, such as a synchronous read.
returns
An event whose value is (Ok v), or (Err e) when thunk raised e.
(sync (blocking #(file-read-text path)))   ; (Result Exception string)

File.ReadAllText, Console.ReadLine, Monitor.Enter: each parks the thread it is called on, and in a fiber that is a pool thread. This runs the thunk through Task.Run, on a thread the pool can grow to replace, and the fiber suspends on the result.

Guarded, so each sync starts a fresh run rather than replaying the initial result. The thunk sees the dynamic environment of the sync.

Not cancellable. What cancellation reaches is the wait: a cancelled scope stops waiting while the thunk carries on to the end, and the scope does not wait for it either.

See also: spawn/thread, sync/blocking

spawn/thread

function ↑ Functions

(: spawn/thread (-> (-> %a) (Event (Result System.Exception %a))))

An event that runs a CPU-heavy thunk on a thread of its own.

thunk
The work: long computation.
returns
An event whose value is (Ok v), or (Err e) when thunk raised e.
(sync (spawn/thread #(resize image 2048)))   ; (Result Exception Image)

A function, not one of the spawn special forms, despite the name: it is written (sync (spawn/thread #(crunch data))). The spawn forms decide who owns a fiber; this decides where work runs.

blocking is for work that parks a thread, this for work that uses a core. It asks .NET for a dedicated thread, which costs about a megabyte of stack and is created and destroyed per call: worth it for work measured in tens of milliseconds, a loss for work measured in microseconds.

Guarded, so each sync starts a fresh thread. Not cancellable: a cancelled scope stops waiting, the thread carries on to the end, and the scope does not wait for it.

See also: blocking, spawn-thunk

spawn-evt/start

function ↑ Functions

(: spawn-evt/start (-> (-> (Promise %a)) (Event (Result System.Exception %a))))

What (spawn-evt (f x)) becomes: start a fiber at the sync, cancel it if the branch loses.

start
A thunk holding the spawn.
returns
An event whose value is the fiber's (Ok v) or (Err e).

The parser turns (spawn-evt (f x)) into a call of this over a thunk holding the spawn. It is not meant to be called by hand.

At each sync the child is started under a cancellation token of its own, not linked to the ambient one, installed as current-cancel around the spawn so that the whole subtree inherits it. The child still goes into the current scope, which waits for it. If the branch loses its choose, the token fires with (Requested "spawn-evt: the branch lost its choose"). (promise-join (bjo (f x))), by contrast, starts eagerly and a lost choose only stops the listening.

Cancellation is still cooperative: a child that never syncs runs to the end.

See also: promise-join, with-nack

make-cancel

function ↑ Functions

(: make-cancel (-> (Tuple (-> CancelReason void) CancelToken)))

A cancel thunk and the token it fires.

returns
A tuple: the thunk, which takes a reason and fires the token, and the token.
(def (Tuple cancel token) (make-cancel))
(spawn (worker token))
(cancel (Requested "shutdown"))

Two values because they are two rights: whoever holds the thunk can cancel, whoever holds the token can only notice. A worker handed the token can watch for its own end without being able to stop its siblings.

Cancelling twice does nothing, so the token carries the first reason it was given.

See also: cancelled, cancelled?, cancel-reason, link-cancel, with-cancel

cancelled

function ↑ Functions

(: cancelled (-> CancelToken (Event CancelReason)))

The event of a token having fired, carrying the reason.

token
The token.
returns
An event whose value is the reason the token was fired with.
(sync (choose (wrap (chan-recv jobs) #(Job &))
              (wrap (cancelled token) #(Stop &))))

An event rather than a callback, so a token can be raced against real work. A token fires once and stays fired, so after it fires this commits at once at every sync: a loop that offers it has to leave when it wins.

See also: until-cancelled, cancelled?, choose

cancelled?

function ↑ Functions

(: cancelled? (-> CancelToken bool))

Polls whether a cancellation token has fired, without waiting.

token
The token.
returns
#t once it has fired.

The poll, for a compute loop with no sync to hang a choose on. A loop that neither syncs nor checks runs to the end whoever cancelled it.

See also: cancel-reason, cancelled

cancel-reason

function ↑ Functions

(: cancel-reason (-> CancelToken (Option CancelReason)))

Why a token fired, if it has.

token
The token.
returns
(Some reason), or None while it has not fired.

A loop tests with cancelled? and, having left, asks this what cleanup it owes.

See also: cancelled?, Requested

until-cancelled

function ↑ Functions

(: until-cancelled (-> CancelToken (Event %a) (Event (Option %a))))

An event, or None if a token fires first.

token
A token other than the ambient one.
ev
The event.
returns
An event whose value is (Some v) when ev commits, and None when token has fired.
(match (sync (until-cancelled deadline (chan-recv jobs)))
  ((Some job) (handle job))
  (None (give-up)))

For a per-request deadline, a sub-scope’s token, or one received from elsewhere. None rather than a raise because a fired token stays fired: a loop that raced one directly would win on it every iteration and spin, and with None leaving is the natural spelling.

ev is offered first, so a token that has already fired does not take an iteration in which ev was ready.

Do not hand it the ambient token. sync already watches that one, and the two would race: whichever commits first decides between None and a raise.

See also: cancelled, choose

function ↑ Functions

(: link-cancel (-> CancelToken CancelToken void))

Makes one token fire when another does.

parent
The token whose firing is passed on.
child
The token fired with the parent's reason.

One way only: firing the child says nothing to the parent. A tree of tokens is repeated linking, and a leaf that is cancelled cancels only what hangs below it.

See also: make-cancel

Requested

function ↑ Functions

(: Requested (-> string CancelReason))

A cancellation reason: someone asked to stop.

who
Who asked, or why. A diagnostic, not something to dispatch on.
returns
The reason.

The cancellation reasons are a closed set: Requested, Deadline, Scope-Ended and Failed. A library cannot add one, and Requested is the case for everything the other three do not name.

See also: Deadline, Scope-Ended, Failed, make-cancel

Failed

function ↑ Functions

(: Failed (-> System.Exception CancelReason))

A cancellation reason: the scope’s body, or a child, raised.

e
The exception.
returns
The reason.

See also: with-cancel, Requested

current-scope

function ↑ Functions

(: current-scope (-> Scope))

The ambient scope, as a value.

returns
The innermost scope the caller is running in.
raises Bjolang.Runtime.ScopeEnded
When there is none: during module initialisation, or in a callback from .NET.

For in-scope, and for a callback that has to capture one. main runs in a scope, so there is one everywhere else.

See also: in-scope, own!

own!

function ↑ Functions

(: own! (-> (-> void) Owned))

Registers a release on the ambient scope.

thunk
What releases the resource. It runs once, when the scope closes or at release!.
returns
The handle that runs it early, through release!.
raises Bjolang.Runtime.ScopeEnded
When there is no ambient scope, or the scope has already run its releases.
(ignore (own! (fun () (release-the-permit))))

For what the GC cannot price: OS handles, permits, subscriptions, state that has to be put back. Not for memory.

Releases run when the scope closes, after every fiber it waits for has landed, newest first, with a fresh token installed so that they are not cancelled. A release that throws is recorded and the rest still run.

A release is a plain thunk: it cannot suspend and has no deadline, so one that blocks blocks the close.

A closing scope still accepts an own! until its releases have run, so a child opening a file during the drain is covered. After that it raises, since nothing would release the resource. A file opened in a spawned fiber belongs to the enclosing scope, not to the fiber.

See also: release!, own-disposable, with-scope, in-scope

release!

function ↑ Functions

(: release! (-> Owned void))

Runs an owned release now, and takes it off its scope.

owned
The handle returned by own!.

A second call does nothing, and so does one that lost the race with the scope’s own closing pass: the thunk runs exactly once either way. When it runs here, on the caller’s stack, its exception reaches the caller.

See also: own!

scope-open!

function ↑ Functions

(: scope-open! (-> long Scope))

A new scope linked to the ambient one. Internal to the scope forms.

ms
A deadline in milliseconds, or zero for none.
returns
The scope, not yet installed.

Cancelling the ambient token cancels this scope; this scope cancelling itself says nothing to its parent. When ms is more than zero, a timer fires the scope’s token with Deadline.

What with-scope and with-cancel expand to, through scope-form; with-deadline opens the same scope with a deadline that is always there. Not meant to be called directly: an install needs a close that a finally guards.

See also: scope-form, with-cancel, shield-open!

shield-open!

function ↑ Functions

(: shield-open! (-> long Scope))

A new scope with no link to the ambient one. Internal to with-shield.

ms
A deadline in milliseconds, more than zero.
returns
The scope, not yet installed.

What with-shield expands to. Not meant to be called directly.

See also: with-shield, scope-open!

scope-push!

function ↑ Functions

(: scope-push! (-> Scope DynEnv))

Installs a scope as the ambient one, returning the displaced environment.

s
The scope.
returns
The environment to hand back to dyn-restore!.

Binds the scope and current-cancel together, so that a spawn and a sync inside it always mean the same cancellation. What scope-form and in-scope expand to; not meant to be called directly.

See also: dyn-restore!, scope-form, in-scope

scope-canceller

function ↑ Functions

(: scope-canceller (-> Scope (-> CancelReason void)))

The thunk that fires a scope’s token. Internal to the scope forms.

s
The scope.
returns
A function taking the reason to fire the token with.

What the cancel of with-cancel is bound to. Firing an already fired token does nothing.

See also: scope-cancel!, with-cancel, make-cancel

scope-token

function ↑ Functions

(: scope-token (-> Scope CancelToken))

A scope’s cancellation token.

s
The scope.
returns
The token the scope installs as current-cancel.

See also: current-scope, until-cancelled, cancel-reason

scope-close!

function ↑ Functions

(: scope-close! (-bjo-> Scope (Option System.Exception) void))

Ends a scope: waits for its children, releases what it owns, and reports. Internal to the scope forms.

s
The scope.
failure
The exception the body is leaving with, or None.

With a failure, the token fires with (Failed e) first. Then the scope is marked closing, and from then on a spawn into it starts nothing; if a child had already failed, the token fires with that child’s Failed now. It waits for every child without watching any token, fires the token with Scope-Ended, stops the deadline timer, and runs the releases newest first. Then it raises what the children and the releases raised: one failure as itself, several, or any beside the body’s, as one System.AggregateException. The body’s failure alone is not raised here; scope-form raises it again.

What scope-form expands to; not meant to be called directly.

See also: scope-form, with-cancel

scope-close!/blocking

function ↑ Functions

(: scope-close!/blocking (-> Scope (Option System.Exception) void))

scope-close! for ordinary code: parks the thread until the scope has ended. Internal to the scope forms.

s
The scope.
failure
The exception the body is leaving with, or None.

Does what scope-close! does, and parks the thread while it waits. What scope-form expands to in a defun or a (fun ...); not meant to be called directly.

See also: scope-close!, scope-form

scope-cancel!

function ↑ Functions

(: scope-cancel! (-> Scope CancelReason void))

Fires the token of a scope held as a value.

s
The scope.
reason
The reason to fire it with.

What the cancel thunk does. Firing an already fired token does nothing.

See also: scope-canceller, current-scope

scope-owned-count

function ↑ Functions

(: scope-owned-count (-> Scope int))

How many releases a scope still holds.

s
The scope.
returns
The number of handles registered and not yet released.

A test hook: std/simpletest fails a test that left one behind.

See also: own!, release!

dyn-restore!

function ↑ Functions

(: dyn-restore! (-> DynEnv void))

Puts back a dynamic environment saved earlier. Internal to the forms that bind one.

env
The environment returned by scope-push! or parameter push.

The other half of scope-push!, and of the push parameterize expands to. scope-form, in-scope and parameterize call it in a finally. Not meant to be called directly.

See also: scope-push!, in-scope, scope-form

close-owned-or-dispose

function ↑ Functions

(: close-owned-or-dispose (-> %a void))

Closes what a with-open bound: through its owner if a scope owns it, by disposing it if not.

x
The value the binding held.

The exit the parser writes for with-open, which binds anything an import/class can produce. A port or connection its scope owns is released through the owner handle, so the registration does not stay on the scope’s list. Anything else disposable is disposed. A standard port is flushed and left open.

Not meant to be called directly.

See also: release!, own-disposable

ticks->duration

function ↑ Functions

(: ticks->duration (-> long Duration))
(ticks->duration t)

The duration of a number of 100 ns ticks.

t
Ticks, as a .NET TimeSpan counts them.
returns
The duration.
raises System.OverflowException
When t is long's minimum, the one tick count with no negation.

See also: duration-ticks

duration-ticks

function ↑ Functions

(: duration-ticks (-> Duration long))
(duration-ticks d)

A duration’s length in 100 ns ticks.

d
The duration.
returns
The ticks, a long.

See also: ticks->duration

milliseconds

function ↑ Functions

(: milliseconds (-> long Duration))
(milliseconds n)

A number of milliseconds, as a duration.

n
Milliseconds.
returns
The duration.
raises System.OverflowException
When n is outside ±29 227 years.

See also: seconds, minutes, hours, Duration

seconds

function ↑ Functions

(: seconds (-> long Duration))
(seconds n)

A number of seconds, as a duration.

n
Seconds.
returns
The duration.
raises System.OverflowException
When n is outside ±29 227 years.
(with-deadline (seconds 5) (fetch url))

See also: milliseconds, minutes, hours, with-deadline, timeout

minutes

function ↑ Functions

(: minutes (-> long Duration))
(minutes n)

A number of minutes, as a duration.

n
Minutes.
returns
The duration.
raises System.OverflowException
When n is outside ±29 227 years.

See also: milliseconds, seconds, hours

hours

function ↑ Functions

(: hours (-> long Duration))
(hours n)

A number of hours, as a duration.

n
Hours.
returns
The duration.
raises System.OverflowException
When n is outside ±29 227 years.

See also: milliseconds, seconds, minutes

duration->timer-ms

function ↑ Functions

(: duration->timer-ms (-> Duration long))
(duration->timer-ms d)

The milliseconds a timer waits for a duration.

d
The duration.
returns
The milliseconds, a long: 0 for zero or less, and a part of a millisecond counted as a whole one.

What with-deadline and with-shield give the scope openers. A part of a millisecond counts as a whole one, so a positive duration does not become zero, which a timer takes as a time already passed.

See also: timeout, with-deadline, Duration

make-clock

function ↑ Functions

(: make-clock (-> (#:monotonic-ms (-> long)) (#:monotonic-ns (Option (-> long))) (#:utc-ticks (-> long)) (#:zone (-> System.TimeZoneInfo)) (#:advance (Option (-> long void))) Clock))
(make-clock #:monotonic-ms clock-ms #:monotonic-ns None #:utc-ticks system-utc-ticks
                   #:zone system-zone #:advance None)

A clock, with each part not given taken from the system’s.

#:monotonic-ms
Reads the monotonic milliseconds.
#:monotonic-ns
Reads the monotonic nanoseconds, or None: then they are the milliseconds times a million.
#:utc-ticks
Reads the wall clock in .NET ticks, UTC.
#:zone
Function returning the local time zone.
#:advance
Moves the clock on by a number of ticks, or None.
returns
The clock.
(parameterize ((current-clock (make-clock #:monotonic-ms (fun () 0L))))
  (time-the-thing))   ; every stopwatch inside reads 0

(std datetime) has fixed-clock, manual-clock and clock-in for the clocks a test wants.

A clock given only #:monotonic-ms reads its nanoseconds from those milliseconds, so a fake clock gives the same exact elapsed time in both units. Any other clock given no #:monotonic-ns, such as one given only #:utc-ticks, therefore has nanoseconds of millisecond resolution. system-clock has the timer’s own.

See also: Clock, system-clock, current-clock

monotonic-ms

function ↑ Functions

(: monotonic-ms (-> (#:clock Clock) long))
(monotonic-ms #:clock (parameter-ref current-clock))

The clock’s monotonic reading, in milliseconds.

#:clock
The clock to read.
returns
Milliseconds from an unspecified start. Only differences mean anything.

For measuring how long something took. Not the wall-clock time, which is (std datetime)’s now. For what takes less than a millisecond, use monotonic-ns.

See also: current-clock, Clock

monotonic-ns

function ↑ Functions

(: monotonic-ns (-> (#:clock Clock) long))
(monotonic-ns #:clock (parameter-ref current-clock))

The clock’s monotonic reading, in nanoseconds.

#:clock
The clock to read.
returns
Nanoseconds from an unspecified start. Only differences mean anything.

The same clock as monotonic-ms, at the resolution the clock has: on system-clock, the resolution of System.Diagnostics.Stopwatch. (std stopwatch) measures with it.

See also: monotonic-ms, current-clock, Clock

SSym

function ↑ Functions

(: SSym (-> Symbol Syntax))

An identifier, as a Syntax.

s
Its name.
returns
The identifier. Built in a transformer, it is renamed by hygiene.

SSym and SDatum carry the same payload and mean opposite things to hygiene: an SSym a transformer constructs is renamed apart from the call site, an SDatum never is. An identifier made from a string, (SSym (string->symbol ...)), is renamed like any other the transformer builds; inject makes one that binds at the call site.

See also: SDatum, syntax-ident=?

SDatum

function ↑ Functions

(: SDatum (-> Symbol Syntax))

A quoted symbol written as data, ‘foo, as a Syntax.

s
The symbol.
returns
The datum. Never renamed by hygiene: it is a value, not a reference to a binding.

See also: SSym

SInt

function ↑ Functions

(: SInt (-> string Syntax))

A numeric literal, as a Syntax.

text
The literal as written, such as "1" or "1.5".
returns
The literal.

Text rather than a number, since the same case carries 1 and 1.5 and which one it is has not been decided when a macro runs.

SStr

function ↑ Functions

(: SStr (-> string Syntax))

A string literal, as a Syntax.

text
The string.
returns
The literal.

SChar

function ↑ Functions

(: SChar (-> char Syntax))

A character literal, as a Syntax.

c
The character.
returns
The literal.

SKey

function ↑ Functions

(: SKey (-> Keyword Syntax))

A keyword such as #:when, as a Syntax.

k
The keyword.
returns
The keyword as syntax.

SList

function ↑ Functions

(: SList (-> (List Syntax) Syntax))

A parenthesized form, as a Syntax.

items
What is inside it, in order.
returns
The form.
(match form
  ((SList (Cons _ (Cons only Nil))) ...)   ; exactly one argument
  ((SList (Cons _ rest)) ...))             ; any number

It holds a real (List Syntax), so map, folds and the trailing rest pattern work on a macro’s input.

SPunct

function ↑ Functions

(: SPunct (-> string Syntax))

A punctuation token that survives reading, as a Syntax.

text
Its spelling: , ,@ : . or ....
returns
The token.

These are not identifiers and not data, but they reach a macro: a comma is an optional argument separator, (: name type) is a signature and ... is a rest pattern. Carrying the spelling is what lets an input form be handed back exactly as it was read.

syntax-error

function ↑ Functions

(: syntax-error (-> Syntax string Syntax))

Rejects a macro’s input with a message; never returns.

form
The syntax the message is about. It is quoted in the message.
msg
What is wrong, and preferably how the macro is written.
returns
Nothing: it throws. Typed as Syntax so it can appear in expression positions returning Syntax.
raises System.InvalidOperationException
Always, with the message followed by the form.
(syntax-match form
  ((_ x) #'(let ((v ,x)) (+ v v)))
  (bad (syntax-error bad "twice takes one argument.")))

How a transformer rejects its input. The expander catches the exception and reports the message against the macro’s call site.

See also: syntax-at, syntax->string

syntax-at

function ↑ Functions

(: syntax-at (-> Syntax Syntax Syntax))

A form carrying the source position of another piece of syntax.

form
The form, usually one a transformer built.
source
A piece of the input, whose position is copied.
returns
form with source's position, or form unchanged when source has none.

Everything a transformer builds is reported at the macro’s call site. With this, an error in code built from one argument points at that argument instead: get and set use it to report an error at the step that caused it. A position can only be copied from input, never made up.

See also: syntax-line, syntax-file

syntax-file

function ↑ Functions

(: syntax-file (-> Syntax string))

The file a piece of syntax was read from.

s
The syntax.
returns
The file's path, or "<unknown>" for syntax with no position, such as what a transformer has just built.

See also: syntax-line, syntax-at

syntax-line

function ↑ Functions

(: syntax-line (-> Syntax int))

The line a piece of syntax starts on.

s
The syntax.
returns
The line, or 0 for syntax with no position, such as what a transformer has just built.

See also: syntax-file, syntax-at

syntax-ident=?

function ↑ Functions

(: syntax-ident=? (-> Syntax Syntax bool))

Whether two pieces of syntax are the same identifier.

a
The first.
b
The second.
returns
#t when both are identifiers or quoted symbols with the same base name; #f otherwise, including when either is not one.

The value-level compare: the test a transformer gets as its third parameter, available to any code. A syntax-match pattern’s 'name compiles to a call to it.

Names are compared with hygiene marks stripped, so an identifier built by one macro and handed to another is still recognised. A quoted symbol counts, so 'else matches an input that wrote else or 'else. It is not denotational equality: a name the caller has rebound locally still compares equal.

See also: SSym, SDatum

syntax->string

function ↑ Functions

(: syntax->string (-> Syntax string))

Renders a piece of syntax back to something that reads as source.

s
The syntax.
returns
Its source text: a list in parentheses with its items separated by spaces, a quoted symbol with its quote, a string in quotes with its quotes and backslashes escaped.

What a macro’s error message wants to quote.

See also: syntax-error

syntax-resolved

function ↑ Functions

(: syntax-resolved (-> Symbol Syntax))

An identifier that hygiene leaves alone and that resolves where the template was written.

s
Its name.
returns
An identifier with the resolved origin.

What the str and displayed of a #"..." written inside a #' template desugar to. The expander lowers it back to a reference no binding at the call site can capture. It is what the compiler writes for a template, not meant to be called directly.

See also: SSym

syntax-splice

function ↑ Functions

(: syntax-splice (-> (List Syntax) (List Syntax) (List Syntax)))

Two lists of syntax, one after the other: what a splice in a template compiles to.

a
The items before.
b
The items after.
returns
The items of a followed by those of b.

The append behind ,@ in a #' template. It is what the compiler writes, not meant to be called directly; it works without the prelude’s own list functions, which a module compiled without the prelude does not have.

Values

unit

value ↑ Values

(: unit void)

The single value of type Unit.

Used when an expression or function body must evaluate to Unit without performing meaningful work, such as in Discard’s blanket implementation. Equivalent to (begin). Not to be confused with (Tuple), which is the empty tuple.

See also: ignore

None

value ↑ Values

(: None (Option %a))

The Option that holds nothing.

(match (map-try-ref m k)
  ((Some v) v)
  (None 0))

See also: Some, none?, option-ref-or

int-max

value ↑ Values

The largest int, 2147483647.

System.Int32.MaxValue. It is up-from’s default #:to, and exported because a default is evaluated where the call is written.

See also: int-min, up-from

int-min

value ↑ Values

The smallest int, -2147483648.

System.Int32.MinValue, down-from’s default #:to.

See also: int-max, down-from

Nil

value ↑ Values

(: Nil (List %a))

The empty list.

(match xs
  (Nil "empty")
  ((Cons _ _) "not empty"))

The other case of a list, with Cons. It is a value, not a function: written Nil, not (Nil).

See also: Cons, list-empty, list-empty?

op/fs-info

value ↑ Values

(: op/fs-info (Param (-> string (Option FsInfo))))

The parameter holding the handler fs-info calls.

with-handler binds it when it installs a handler for fs-info, and (handler-of fs-info) reads it. Under a prefix or a rename, where with-handler cannot derive this name from the operation’s, parameterize it directly. Cold: it takes none of the dynamic environment’s cheap parameter ids.

See also: fs-info, fs-info/raw

op/fs-list

value ↑ Values

(: op/fs-list (Param (-> string (Result Exception (Vec string)))))

The parameter holding the handler fs-list calls.

with-handler binds it when it installs a handler for fs-list, and (handler-of fs-list) reads it. Cold.

See also: fs-list, fs-list/raw

op/fs-create-directory

value ↑ Values

(: op/fs-create-directory (Param (-> string (Result Exception Unit))))

The parameter holding the handler fs-create-directory calls.

with-handler binds it when it installs a handler for fs-create-directory. Cold.

See also: fs-create-directory, fs-create-directory/raw

op/fs-delete-file

value ↑ Values

(: op/fs-delete-file (Param (-> string (Result Exception Unit))))

The parameter holding the handler fs-delete-file calls.

with-handler binds it when it installs a handler for fs-delete-file. Cold.

See also: fs-delete-file, fs-delete-file/raw

op/fs-delete-directory

value ↑ Values

(: op/fs-delete-directory (Param (-> string (Result Exception Unit))))

The parameter holding the handler fs-delete-directory calls.

with-handler binds it when it installs a handler for fs-delete-directory. Cold.

See also: fs-delete-directory, fs-delete-directory/raw

op/fs-move

value ↑ Values

(: op/fs-move (Param (-> string string MoveMode (Result Exception Unit))))

The parameter holding the handler fs-move calls.

with-handler binds it when it installs a handler for fs-move. Cold.

See also: fs-move, fs-move/raw

op/getenv

value ↑ Values

(: op/getenv (Param (-> string (Option string))))

The parameter holding the handler getenv calls.

with-handler binds it when it installs a handler for getenv, and (handler-of getenv) reads it. Under a prefix or a rename, parameterize it directly. Cold: it takes none of the dynamic environment’s cheap parameter ids.

See also: getenv

current-input-port

value ↑ Values

(: current-input-port (Param Bjolang.Runtime.BjoInputPort))

The port standard input is read from.

(read-line (parameter-ref current-input-port))

A (Param InputPort), read with parameter-ref and rebound with parameterize. There is no read without a port: standard input is read as any other port is.

Its default is standard input, buffered once for the whole program, so port-eof? on it usually costs no system call. Closing it does nothing.

It is a port over standard input’s raw bytes, as every port is: its text reads decode UTF-8 whatever the console’s encoding, and its byte reads work on piped binary input. On a terminal the terminal edits and echoes each line, and Ctrl-D at the start of a line is end of input.

See also: current-output-port, read-line, port-eof?

current-output-port

value ↑ Values

(: current-output-port (Param Bjolang.Runtime.BjoOutputPort))

The port display, displayln and newline write to.

(def out (open-output-string))
(parameterize ((current-output-port out))
  (display "captured"))
(get-output-string out)   ; "captured"

A (Param OutputPort). Its default is standard output, which the runtime does not buffer. Binding it with parameterize redirects display, displayln, newline, print and println.

close-output-port on standard output flushes it and does nothing more.

See also: current-error-port, display, write-string

current-error-port

value ↑ Values

(: current-error-port (Param Bjolang.Runtime.BjoOutputPort))

The port for errors and diagnostics, standard error by default.

A (Param OutputPort). The default handlers of warn and log write a line to it. close-output-port on standard error flushes it and does nothing more.

See also: current-output-port, warn, log

op/open-read-stream

value ↑ Values

(: op/open-read-stream (Param (-> string (Result Exception Stream))))

The parameter holding the open-read-stream operation’s handler.

What (with-handler ((open-read-stream h)) ...) binds. It is cold: files are not opened in a loop, so it spends none of the cheap parameter ids. Bind it with parameterize directly when the operation was imported under another name, so that with-handler cannot find the cell by spelling.

See also: open-read-stream, open-read-stream/raw

op/open-write-stream

value ↑ Values

(: op/open-write-stream (Param (-> string WriteMode (Result Exception Stream))))

The parameter holding the open-write-stream operation’s handler.

What (with-handler ((open-write-stream h)) ...) binds. It is cold, like the other operations of the FS effect.

See also: open-write-stream, open-write-stream/raw

op/warn

value ↑ Values

(: op/warn (Param (-> string void)))

The parameter holding the warn operation’s handler.

What (with-handler ((warn h)) ...) binds. Bind it with parameterize directly when warn was imported under another name, so that with-handler cannot find the cell by spelling.

See also: warn

op/log

value ↑ Values

(: op/log (Param (-> string void)))

The parameter holding the log operation’s handler.

(parameterize ((p:op/log collect)) ...)

What (with-handler ((log h)) ...) binds. Bind it with parameterize directly when log was imported under a prefix or another name, so that with-handler cannot find the cell by spelling.

See also: log

current-cancel

value ↑ Values

(: current-cancel (Param CancelToken))

The ambient cancellation token, which every sync watches.

A (Param CancelToken). A scope installs its token here for its body, and a spawned fiber starts with the environment it was spawned in, so the whole subtree sees the same token without one being passed anywhere.

Outside every scope it is a token that never fires. Inside a with-shield it is the shield’s own, which a cancellation outside the shield does not fire.

A bare (parameterize ((current-cancel t)) ...) binds the token without changing which scope a spawn goes into.

See also: sync, cancelled?, with-cancel, current-scope

Deadline

value ↑ Values

(: Deadline CancelReason)

A cancellation reason: a time limit ran out.

What the timer of with-deadline or with-shield fires its scope’s token with.

See also: with-deadline, with-shield, Requested

Scope-Ended

value ↑ Values

(: Scope-Ended CancelReason)

A cancellation reason: the scope owning the token has finished.

A scope fires its token with this once every child it waits for has landed, unless the token fired earlier, so a daemon or a fiber handed the token stops rather than outliving the scope.

See also: with-cancel, Requested

system-clock

value ↑ Values

(: system-clock Clock)

The machine’s clock, in the machine’s zone.

See also: current-clock, make-clock

current-clock

value ↑ Values

(: current-clock (Param Clock))

The clock monotonic-ms and (std datetime) read.

A cold (Param Clock), starting as system-clock. Binding it fixes both monotonic-ms and (std datetime)’s now and today.

See also: system-clock, make-clock, monotonic-ms

currently-in-repl

value ↑ Values

(: currently-in-repl (Param bool))

Whether the code is running in a REPL.

A cold (Param bool): #t while the REPL runs an entry, #f in a built program. panic! reads it, and at a prompt raises instead of ending the process.

See also: panic!

Macros

with-scope

macro ↑ Macros

(with-scope body ...)

Runs body in a scope that waits for its fibers and releases what it owns.

body ...
What to run. Its last value is the form's.
(with-scope
  (match (open-input-file "notes.txt")
    ((Ok p) (read-all p))   ; closed when the scope returns
    ((Err e) "")))

A with-cancel whose cancel thunk nothing in the body can reach: the plain form, and the one to put around resources. It waits for every fiber spawn, bjo or spawn-thunk started in it, then releases what was owned in it, newest first.

In a bjoroutine the wait suspends. In ordinary code, a defun or a (fun ...), it parks the thread, and the blocking lint reports it when a bjoroutine reaches it.

See also: with-cancel, own!, in-scope

with-cancel

macro ↑ Macros

(with-cancel (cancel) body ...)

Runs body in a scope that owns the fibers it starts, with a thunk to cancel them.

cancel
The name the cancel thunk is bound to. It takes a reason.
body ...
What to run. Its last value is the form's.
(with-cancel (cancel)
  (spawn (worker jobs results))
  (def res (sync (chan-recv results)))
  (cancel (Requested "got it"))
  res)

Opens a scope whose token is linked to the ambient one, installs it as the current scope and current-cancel for the body, and closes it on the way out. The binding is restored however the body is left.

The order on the way out. When the body leaves with an exception, the token fires with (Failed e) first; so it does when a child had already failed. Then the scope waits for every child, fires the token with Scope-Ended if it has not fired, and runs its releases newest first. Only then does it report. A scope whose children never end, and which never calls cancel, hangs rather than returning.

A child that fails does not interrupt the body: the token is fired with (Failed e) once the body has ended, as above, or at once if the child fails while the scope is already waiting. Its failure is raised when the scope returns. Several failures, a release that threw among them, are raised together as one System.AggregateException, the body’s first. A child that stopped because it was cancelled has not failed. A bjo child’s failure is its promise’s, and the scope does not raise it again.

In a bjoroutine the wait suspends. In ordinary code it parks the thread, as with-scope’s does.

See also: with-scope, with-deadline, with-shield, Requested, current-cancel

with-deadline

macro ↑ Macros

(with-deadline d body ...)

Runs body in a scope that is cancelled with Deadline after a length of time.

d
A Duration. Zero or less has passed already: the scope is cancelled at once. For no deadline, write with-scope.
body ...
What to run. Its last value is the form's.
(with-deadline (seconds 5)
  (spawn (fetch "a"))
  (spawn (fetch "b")))   ; returns once both have landed or been cancelled

with-cancel with a timer the scope owns. When it fires, the token fires with Deadline, and every sync in the scope that has to wait raises Cancelled. The body has no cancel thunk.

Running out of time is not itself a failure. A child stopped by the deadline has not failed, so the form above returns normally either way; it raises only when the body itself was stopped, or a child failed. A caller that needs to know reads the reason off the scope’s token.

See also: with-cancel, seconds, timeout, Deadline

with-shield

macro ↑ Macros

(with-shield body ...)
(with-shield #:within d body ...)

Runs body in a scope that a cancellation outside it does not reach.

d
The shield's own deadline, a Duration above zero. Thirty seconds when it is not given.
body ...
What to run. Its last value is the form's.
(with-shield #:within (seconds 5)
  (spawn (flush-buffer a))
  (spawn (flush-buffer b)))

How cleanup runs after a cancellation. Once a scope has been cancelled every sync in it raises, including those in the code trying to tidy up. Inside a shield the ambient token is a fresh one, not linked to the parent’s, so a sync works again, and current-cancel agrees with it.

The deadline is not optional: a shield nothing outside can reach and that never times out would make the program impossible to stop. So a duration of zero or less raises System.ArgumentOutOfRangeException. It is a scope, so it waits for its own children.

See also: with-cancel, current-cancel

in-scope

macro ↑ Macros

(in-scope s body ...)

Runs body with a given scope as the ambient one.

s
The scope, from current-scope.
body ...
What to run. Its last value is the form's.
(def home (current-scope))
(on-event (fun (e) (in-scope home (handle e))))

The way to own something in a scope other than the innermost one, and the way back in from a .NET callback, which arrives on a thread with no ambient scope at all.

It installs a scope; it does not open or close one, and it does not suspend. Whoever opened s is still the one that waits for it.

See also: current-scope, own!, with-scope

own-disposable

macro ↑ Macros

(own-disposable x)

Registers an IDisposable’s Dispose method on the ambient scope, returning the resource.

x
An expression evaluating to an object with a .Dispose method.
(def reader (own-disposable (StreamReader. path)))

(own! (fun () (.Dispose x))), returning x. A form so that .Dispose resolves at the call site, as with-open resolves it. with-open is for a resource whose lifetime is one block; this is for one whose lifetime is the scope’s.

See also: own!, with-scope

scope-form

macro ↑ Macros

(scope-form opener (cancel) first body ...)

The shared expansion of with-scope, with-cancel, with-deadline and with-shield.

opener
The call that makes the scope: scope-open! or shield-open!.
cancel
The name the cancel thunk is bound to.
first
The body's first form.
body ...
The rest of the body.

Opens the scope, installs it with scope-push!, binds the thunk from scope-canceller, runs the body, and closes the scope with scope-close! in a bjoroutine and scope-close!/blocking in ordinary code, telling it about the body’s exception if there was one, which is then raised again unless the close raised first. dyn-restore! puts the old environment back however the form is left.

Not meant to be written by hand: use one of the four forms.

See also: with-scope, with-cancel, with-deadline, with-shield

cond

macro ↑ Macros

(cond clause ... (else body ...))

Picks the first clause whose test holds, at any number of arms; the last clause is else.

clause ...

A clause, one of:

(test body ...): evaluates the body when test is true.

(:match pattern expr body ...), or (:match pattern expr #:when guard body ...): evaluates the body when expr matches pattern and the guard, if any, holds.

(:def pattern expr), or (:def pattern expr failure ...): binds locally; does not produce a value.

(:do body ...): runs the body for side effects; does not produce a value.

body ...
The forms evaluated in the else clause; the final form is returned.

Literally: else

(cond ((< n 0) "negative")
      ((= n 0) "zero")
      (else "positive"))

;; A value a later test needs, without a nested cond to hold it
(cond ((string-empty? text) "empty")
      (:def first (string-cursor-ref text (string-cursor-start text)))
      ((char-numeric? first) "number")
      (else "word"))

if at any number of arms. The final else is required, since every arm must evaluate to a value and the branches must be exhaustive; every arm needs the same type. Only the clause that is taken runs. A clause with a test and no body is an error, and so is a clause after the else, which could never be reached.

A :match clause is a test that binds: what its pattern binds is in scope in its guard and body only, and when it does not match the cond goes on to the next clause.

:def and :do do not produce values. Both are reached only when every test above them has failed. A :def binds, and what it binds is in scope in every clause below it and nowhere else. It is a def whose body is the rest of the cond, so it takes the same patterns and the same failure parts: (:def (Ok v) (parse s) :propagate) makes the whole cond the Err, and (:def (Some n) (lookup k) :default 0) binds n either way and never terminates the cond early. A :do runs its forms and goes on. A cond may not end in either.

The else clause unconditionally evaluates its body without looking at anything after it, so clauses written after it are not used.

See also: if-let, when-let

if-let

macro ↑ Macros

(if-let (name expr) then else)

Evaluates then with name bound to the value of an Option, or evaluates else when None.

name
The name bound to the value inside the Some, in then only.
expr
An expression evaluating to an Option. Evaluated once.
then
Expression evaluated when expr is (Some ...).
else
Expression evaluated when expr is None.
(if-let (half (halve n)) half 0)

One binding, written (name expr) without a second pair of parentheses. It is (match expr ((Some name) then) (None else)).

See also: when-let, some->, cond

when-let

macro ↑ Macros

(when-let (name expr) body more ...)

Runs the body with name bound to what an Option holds, when it is not None.

name
The name bound to the value inside the Some, in the body.
expr
An expression evaluating to an Option. Evaluated once.
body
The first form of the body.
more ...
The rest of the body.
(when-let (line (read-line/opt port))
  (println line))

A when: it returns unit (()), discarding the body’s result, which must be droppable. The body does not run when expr is None.

See also: if-let

some->

macro ↑ Macros

(some-> value step ...)

Threads a value through steps as -> does, stopping at the first None.

value
The plain value the first step receives.
step ...
Each step evaluates to an Option, receiving the previous unwrapped value. Threaded as -> threads: first argument, or where & is.
(some-> 8 (halve) (halve))           ; (Some 2)
(some-> 6 (halve) (try-ref [10 20 30 40] &))   ; (Some 40): & says where the value goes
(some-> 5)                           ; (Some 5)

Each step’s Some is unwrapped before the next step is called with what it held. A None immediately short-circuits to None, and subsequent steps do not run. Returns the final step’s Option; with no steps it returns (Some value).

See also: try->, if-let

try->

macro ↑ Macros

(try-> value step ...)

Threads a value through steps as -> does, stopping at the first Err.

value
The plain value the first step receives.
step ...
Each step evaluates to a Result, receiving the previous unwrapped value. Threaded as -> threads: first argument, or where & is.
(try-> path (open-input-file &) (read-header &))

The same shape as some->, over Result. Each step’s Ok is unwrapped before the next step is called with what it held, so a chain reads in the order it runs rather than inside out. An Err immediately short-circuits to that error, and subsequent steps do not run. Returns the final step’s Result; with no steps it returns (Ok value).

See also: some->, result-map

let*

macro ↑ Macros

(let* (binding ...) body ...)

Binds in order, each binding in scope for the ones after it.

binding ...
A binding as let takes it, such as (name expr).
body ...
What to run with them bound. Evaluates to the value of the last form.
(let* ((a 1)
       (b (+ a 1)))
  (* a b))   ; 2

One let per binding, nested, so each expression sees the names bound before it.

See also: parameterize*

parameterize*

macro ↑ Macros

(parameterize* (binding ...) body ...)

Binds parameters in order, each binding in effect for the ones after it.

binding ...
A binding as parameterize takes it: (param expr).
body ...
What to run with them bound. Evaluates to the value of the last form.

The let* of parameterize: one parameterize per binding, nested, so each expression runs with the parameters bound before it already bound. With no bindings it is the body in a let.

See also: let*

get

macro ↑ Macros

(get target)
(get target step ...)

Reads along a path of fields and keys, or reads what a Box or a Param holds.

target
What the path starts from.
step ...
A field step, .name, or a key, which is any other expression.
(get team .players 0 .name)   ; "Ada"
(get counter)                 ; what the Box holds

A step written with a leading dot reads with (.name x), so it is a record or struct field, or a .NET member such as .-Length. Any other step is a key and reads with ref. Which kind a step is depends only on how it is written, since a macro runs before anything has a type. A lone . or ... is not a step and is an error.

With no steps it is (deref target): what a Box or a Param holds, or anything else with a Derefable impl.

Each step’s code carries that step’s source position, so an error in it is reported at the step.

See also: try-get, set, update, ref, deref

try-get

macro ↑ Macros

(try-get target step more ...)

Reads along a path of fields and keys, None at the first key that is missing.

target
What the path starts from.
step
The first step: .name for a field, or a key expression.
more ...
The steps after it.
(try-get team .tags "veg")   ; None

Every key is read with try-ref, so missing is what try-ref says it is: a Map key that is absent, or a Vec index out of range. The keys after a missing one are not evaluated. A field step cannot be missing; a field holding an Option is wrapped inside Some. At least one step is required.

See also: get, try-ref

set

macro ↑ Macros

(set target step more ... value)

A copy of target with a value at the end of a path of fields and keys.

target
What the path starts from. It is left as it was.
step
The first step: .name for a field, or a key expression.
more ...
The steps after it.
value
What goes at the end of the path.
(set team .players 0 .name "Bea")   ; a new Team

Field steps copy with record-set, so only a field of a Bjolang record or struct can be written through; a .-Property step is refused. Key steps copy with ref-set.

The target is evaluated first, then each key from left to right, then the value, each exactly once. The last key is not read, so on a Map it adds a key that was not there; a key missing earlier in the path throws, as ref does.

See also: update, get, ref-set

update

macro ↑ Macros

(update target step more ... f)

A copy of target with a function applied to the value at the end of a path.

target
What the path starts from. It is left as it was.
step
The first step: .name for a field, or a key expression.
more ...
The steps after it.
f
Transformation function applied to the target value; its return value replaces the target.
(update team .players 1 .score (fun (s) (+ s 1)))

set with (f old) at the end of the path, and the same rules: the target, then each key from left to right, then f, each evaluated once; field steps copy with record-set and key steps with ref-set. Every key is read, so a missing one throws.

See also: set, get

type/derive

macro ↑ Macros

(type/derive (trait ...) typedef ...)

Declares types and writes their implementations from the declaration.

trait ...
Eq or Ord for a record, a struct or a union; any trait for a newtype.
typedef ...
A type declaration as type takes it, (: Name (Record ...)): a record, a struct, a union or a newtype.
(type/derive (Eq Ord)
  (: Version (Record (: major int) (: minor int))))

(list-sort versions)

It expands to the type form it was given and one impl per trait and type. It is syntactic: it reads only the declaration, not a registry of types.

Eq: a record or struct compares its fields in declaration order; a union compares the case first, so different cases are unequal, and the same case compares its payload positionally. The hash combines the fields’ hashes. A record or struct with a #:mutable field has no lawful hash, so its eq-hash is unhashable, which throws naming the type: equality works, but it cannot be a key.

Ord: a record or struct compares its fields in declaration order and stops at the first that decides; a union compares the case index before the payload.

A newtype, (: Name (Newtype T)), gets (impl (trait Name) #:via T) for each trait: the implementation of the type it wraps, which is the same value at run time.

A type with parameters gets a conditional implementation, with a where of the trait being derived for each parameter: (where (Eq %a)) for Eq, (where (Ord %a)) for Ord. A field whose type has no implementation is reported against the type/derive form. An alias cannot derive: derive for the type it names.

Has

macro ↑ Macros

(Has key pattern)

A pattern matching a collection that holds a key, with a pattern for its value.

key
The key to look up, an expression.
pattern
The pattern the value at that key must match.
(match config
  ((Has "port" p) p)
  (_ 8080))

(:view (try-ref & key) (Some pattern)): the key is looked up with try-ref, and the pattern is tried on what it finds. A view covers nothing for the exhaustiveness check, so a match on it needs another arm.

See also: Has*, try-ref

Has*

macro ↑ Macros

(Has* (key pattern) ...)

A pattern matching a collection that holds every one of several keys.

key
A key to look up, an expression.
pattern
The pattern the value at that key must match.
(match config
  ((Has* ("host" h) ("port" p)) (connect h p))
  (_ (connect "localhost" 8080)))

An (and ...) of one Has per pair. At least one pair is required.

See also: Has

#fl

reader extension ↑ Macros

#fl(op a b more ...)

Folds a binary operator over its operands from the left.

op
A binary operator or function.
a
The first operand.
b
The second operand.
more ...
Further operands.
#fl(- 10 3 2)   ; (- (- 10 3) 2), 5

#fl(op a b c) is (op (op a b) c), for any binary op. Fewer than two operands is an error. #fr is the right fold and #ch the chain. The parser hands an arithmetic or bitwise operator with three or more operands to it: (+ a b c) is #fl(+ a b c).

#fr

reader extension ↑ Macros

#fr(op a b more ...)

Folds a binary operator over its operands from the right.

op
A binary operator or function.
a
The first operand.
b
The second operand.
more ...
Further operands.
#fr(Cons 1 2 Nil)   ; (Cons 1 (Cons 2 Nil))

#fr(op a b c) is (op a (op b c)), for any binary op. Fewer than two operands is an error. #fl is the left fold, and the one the parser uses.

#ch

reader extension ↑ Macros

#ch(op a b more ...)

Chains a comparison over its operands: (op a b), then (op b c), and so on.

op
A binary comparison.
a
The first operand.
b
The second operand.
more ...
Further operands.
#ch(< 0 i n)            ; (< 0 i), then (< i n) if that held
#ch(< 0 (next!) 10)     ; (next!) is called once

Each comparison is tested only if the one before it held, and the first that fails returns #f without evaluating subsequent operands. A middle operand that is not an atom is bound once, right before its first use, so nothing is evaluated twice. Fewer than two operands is an error.

The parser hands a comparison operator with three or more operands to it: (< a b c) is #ch(< a b c).

#set!

reader extension ↑ Macros

#set!(target step ... value)

Writes along a path in place: the form that set! with three or more operands is.

target
The collection or record to write into.
step ...
A key, or .field. The last one is written, and the ones before it are read.
value
What the last step is set to.
(set! counts "a" 5)            ; (ref-set! counts "a" 5)
(set! grid 2 3 #\\#)            ; row 2 is read, its key 3 is written
(set! state .players 0 .score 10)

The parser hands set! with three or more operands here, and keeps (set! name value), which writes a variable. Nothing is copied. A key is written with ref-set! (Settable!) and a field with record-set!, so the field has to be #:mutable. The target, each key from left to right, and then the value are each evaluated once, before anything is read.

See also: ref-set!, deref-set!

#map

reader extension ↑ Macros

#map()
#map(entry ...)

A Map literal.

entry ...
A key and its value, written (k v), [k v] or (k . v).
#map(("a" 1) ["b" 2] ("c" . 3))
#map()                           ; (map-empty)

(list->map ...) of the entries as tuples, and #map() is (map-empty). A name of its own beside the function map.

See also: map-empty, list->map