Overview
The part of the prelude that does not reach the operating system: collections, strings, characters, iteration and printing to a string.
(import (std prelude core))
(def words (string-split "a b c" " "))
(vec-length words) ; 3
(loop (:for w words) (:acc (summing (string-length w)))) ; 3
(std prelude) imports this module and re-exports all of it, so a
program has its names without an import. Import it in place of
(std prelude) only in a module that (std prelude) itself
depends on.
What is here. Lists, vecs, maps and arrays, strings, characters
and string cursors, the Iterable, Collection and
Collector traits, range and the collectors,
Written and Displayed, options and results, and the
macros if-let, when-let, some->, try->,
let*, parameterize* and type/derive, the
acc-clauses such as oring, the hash macros #fl,
#fr, #ch, #map and #set!, the path macros
get and set, and the patterns Has and Has*.
What is not. Ports, files, directories and the process
environment, effects, the clock and durations, cancellation scopes and
select are in (std prelude).
See also: list-map, vec-map, map-ref, str, written, fold, range
Reference
ArrayingArraySliceBoxChainedCountingCursorCycledDecodeErrorDisplayedDownFromEncodingEnumeratedExceptionFoldingGroupingPairsIArrayInputPortIterableListingListingReverseListTailsMapMapBuilderMapCursorMappingMaximizingMaximizingPairsMinimizingMinimizingPairsOutputPortPairwisePortReadsRangeRangeByRepeatedReverseArraySliceReverseVecSliceRoSpanSpanStringingStringWalkSummingTallyingTransientMapTransientVecUpFromUtf8ChunkVecBackCursorVecingVecingSmallVecSliceWrittenZipped
->list->map->seq->str->vecaddadd!add-alladd-all!all?any?array->iarrayarray->ro-spanarray->spanarray-contains?array-copy!bigint->stringblock-countblock-growblock-none!block-spanbox-refbox-set!byte->stringbytes->stringbytes->string/lossybytes->utf8-chunkbytes-utf-8?chainchar<=?char<?char=?char>=?char>?collector-finishcollector-initcollector-stepcontiguous-validcontiguous-valuescontiguous?countcursor-endcursor-end?cursor-nextcursor-prevcursor-refcursor-startdecimal->stringdecode-error-messagederefderef-set!display-intodisplayeddouble->stringdown-fromdropdrop-whileelements-print-intoempty?entries-print-intoenumerateerr?filterfindfirstflat-mapfoldfor-eachfstgrammar-checkediarray->arrayiarray->listiarray->seqiarray->veciarray-addiarray-contains?iarray-emptyiarray-empty?iarray-lengthiarray-mapiarray-refiarray-setiarray-try-refignorein-arrayin-cyclein-portin-repeatin-reverse-arrayin-reverse-vecin-vecint->stringint128->stringiterable-cleanupiterable-currentiterable-done?iterable-enditerable-nextiterable-startlengthlist->iarraylist->maplist->strlist->stringlist->veclist-appendlist-contains?list-filterlist-foldllist-foldrlist-for-eachlist-maplist-unfoldlong->stringmake-boxmapmap->listmap->mapbuildermap->seqmap->strmap->transientmapmap->vecmap-add-newmap-altermap-any?map-clearmap-contains?map-cursormap-cursor-currentmap-cursor-done?map-cursor-nextmap-emptymap-empty?map-entry->strmap-filtermap-findmap-foldmap-for-eachmap-has-key?map-itermap-keysmap-lengthmap-mapmap-map-valuesmap-mergemap-merge-withmap-refmap-ref-ormap-removemap-remove-allmap-setmap-set-allmap-splitmap-try-add-newmap-try-refmap-updatemap-valuesmapbuilder->mapmapbuilder-add!mapbuilder-add-all!mapbuilder-emptymapbuilder-lengthnumber->stringok?option->resultoption-filteroption-mapoption-orover-listpairwisepanic!printprintlnrangerange-byrefref-setref-set!result->optionresult-mapresult-map-errresult-refresult-ref-orro-span->ro-span->arrayro-span-lengthro-span-refro-span-sliceseq->iarrayseq->mapseq-enumerateseq-foldseq-for-eachsndspan->span->arrayspan->ro-spanspan-lengthspan-refspan-set!span-slicesqrtstrstring->bigintstring->bytesstring->decimalstring->doublestring->intstring->int128string->liststring->longstring->uint128string->vecstring-appendstring-contains?string-copystring-cursor-backstring-cursor-forwardstring-cursor<=?string-cursor<?string-cursor=?string-cursor>=?string-cursor>?string-downcasestring-dropstring-drop-rightstring-drop-right/slicestring-drop/slicestring-ends-with?string-findstring-foldstring-fold-rightstring-for-eachstring-joinstring-lengthstring-pad-leftstring-pad-rightstring-replacestring-reversestring-splitstring-split-oncestring-split-once/slicestring-split/slicestring-starts-with?string-takestring-take-rightstring-take-right/slicestring-take/slicestring-trimstring-trim-leftstring-trim-left/slicestring-trim-rightstring-trim-right/slicestring-trim/slicestring-upcasestring-walkstring-walk-currentstring-walk-done?string-walk-nextsubarray->iarraytaketake-whiletransientmap->maptransientmap-alter!transientmap-contains?transientmap-emptytransientmap-empty?transientmap-filter!transientmap-has-key?transientmap-lengthtransientmap-reftransientmap-ref-ortransientmap-remove!transientmap-remove-all!transientmap-set!transientmap-set-all!transientmap-try-reftransientmap-update!transientvec->vectransientvec-add!transientvec-add-all!transientvec-add-first!transientvec-contains?transientvec-emptytransientvec-empty?transientvec-lengthtransientvec-pop!transientvec-pop-first!transientvec-reftransientvec-set!transientvec-try-pop!transientvec-try-pop-first!try-dereftry-refuint128->stringup-fromutf8-chunk-lengthutf8-chunk-substringutf8-chunk-valid-endvec->arrayvec->iarrayvec->listvec->mapvec->transientvecvec-addvec-add-firstvec-back-cursorvec-back-cursor-currentvec-back-cursor-done?vec-back-cursor-nextvec-contains?vec-dropvec-filtervec-foldvec-for-eachvec-insertvec-itervec-mapvec-reducevec-remove-atvec-reversevec-slicevec-splitvec-takevec-try-popvec-try-pop-firstwrite-intowrittenzip
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).
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-minfor 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.
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.
Maximizing
union ↑ Types
The collector that keeps the greatest value by Ord: (Some x), or None for no steps.
%a- The type of the values.
maximizing- The collector: (maximizing x) keeps x when it is greater than the greatest so far.
{maximizing x (:for x xs)} ; the greatest element, or None
Of equal values the first is kept. To keep a value by a key of it, use
(maximizing-by key x).
See also: Minimizing, MaximizingPairs, maximizing-by
Minimizing
union ↑ Types
The collector that keeps the least value by Ord: (Some x), or None for no steps.
%a- The type of the values.
minimizing- The collector: (minimizing x) keeps x when it is less than the least so far.
{minimizing x (:for x xs)} ; the least element, or None
Of equal values the first is kept. To keep a value by a key of it, use
(minimizing-by key x).
See also: Maximizing, MinimizingPairs, minimizing-by
MaximizingPairs
union ↑ Types
The collector of (Tuple key value)s that keeps the value of the greatest key: (Some value), or None.
%k- The type of the keys, compared by Ord.
%v- The type of the values.
maximizing/pairs- The collector: (maximizing/pairs (Tuple k v)).
Of equal keys the first is kept. (maximizing-by key x) is this
collector of (Tuple key x).
See also: maximizing-by, MinimizingPairs, Maximizing
MinimizingPairs
union ↑ Types
The collector of (Tuple key value)s that keeps the value of the least key: (Some value), or None.
%k- The type of the keys, compared by Ord.
%v- The type of the values.
minimizing/pairs- The collector: (minimizing/pairs (Tuple k v)).
Of equal keys the first is kept. (minimizing-by key x) is this
collector of (Tuple key x).
See also: minimizing-by, MaximizingPairs, Minimizing
Tallying
union ↑ Types
The collector that counts how many times each value comes: a map from value to count.
%a- The type of the values, compared by Eq.
tallying- The collector: (tallying x) adds one to x's count.
{tallying w (:for w words)} ; how many times each word occurs
A value that never comes is not in the map. It is built in a
TransientMap, and made a Map when the loop ends.
See also: Counting, GroupingPairs, grouping
GroupingPairs
union ↑ Types
The collector of (Tuple key value)s that makes a map from each key to the list of its values.
%k- The type of the keys, compared by Eq.
%v- The type of the values.
grouping/pairs- The collector: (grouping/pairs (Tuple k v)).
Each list is in the order its values came. (grouping key x) is
this collector of (Tuple key x). It is built in a
TransientMap of list builders, and made a Map of lists
when the loop ends.
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.
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.
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.
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.
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:accclause, 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:accclause, 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
Arraying
union ↑ Types
The collector that gathers a loop’s values into an array.
%a- The element type.
arraying- The collector itself, written (arraying x) in an :acc clause.
(loop (:for x [1.5 2.5 3.5])
(:acc (arraying (* 2.0 x)))) ; an array of 3.0 5.0 7.0
The array grows as the loop takes values in, and is cut to their number
at the end. Arraying is a BlockCollector, so a loop of
numbers into it can be compiled to vector instructions.
See also: Collector, Vecing, block-grow
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
IArray
type alias ↑ Types
An array that is not written after it is made: built once, then read.
%a- The element type.
(def xs (vec->iarray [1 2 3]))
(ref xs 1) ; 2
(length xs) ; 3
(iarray->vec (iarray-set xs 0 10)) ; [10 2 3], xs is unchanged
(= xs (list->iarray '(1 2 3))) ; #t
A struct around .NET’s ImmutableArray<T>, which holds one array.
Indexing is an array read, a walk reads the array in order, and the
value is one reference wide, where a vec is an object of its own. Every
change copies the whole array, so iarray-add in a loop is
quadratic: build in a MutableVec and convert once with
mutablevec->iarray. A value that changes after it is made is a
Vec.
Equality. Two arrays are equal when they hold equal elements
in the same order, also to .NET: an IArray is a good key in a
Map or a HashSet.
The default value. A field or an array slot of this type that is not written yet holds no array. Every function reads it as the empty array.
Traits. Implements Refable, Collection,
Iterable (an int cursor, as Array has), Eq,
Written and Displayed, which write #iarray[1 2 3].
There is no literal and no pattern.
See also: vec->iarray, subarray->iarray, iarray-ref, iarray-length, iarray-add, iarray-set
Span
type alias ↑ Types
A writable view of part of an array, valid only while the call that made it runs.
%a- The element type.
(: (-> (Span long) long))
(defun (sum s)
(let loop ((i 0) (acc 0L))
(if (< i (span-length s))
(loop (+ i 1) (+ acc (span-ref s i)))
acc)))
(def xs (vec->array [1L 2L 3L 4L]))
(sum (array->span xs #:from 1 #:to 3)) ; 5, and nothing is copied
.NET’s Span<T>. Writes through it change the array it views.
A span can be a local, an argument and a result. The compiler refuses
one where it could outlive the call that made it: in another value, as
a type argument of a generic function, captured by a (fun ...)
or a local function, in scope across a yield point, or as a
module-level definition. Copy it with span->array to keep its
elements.
See also: array->span, span-ref, span-set!, span-slice, span->ro-span, RoSpan
RoSpan
type alias ↑ Types
A read-only view of part of an array, valid only while the call that made it runs.
%a- The element type.
.NET’s ReadOnlySpan<T>, with the rules of Span. A
Span is not converted to one implicitly: use
span->ro-span.
See also: array->ro-span, ro-span-ref, ro-span-slice, span->ro-span, Span
Map
record ↑ 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), written in
Bjolang in lib/std/hashmap.protobjo over the C# nodes of
Bjolang.Runtime.HashTries. 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
record ↑ 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
record ↑ 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
record ↑ 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 returns an error,
bytes->string/lossy and a port put U+FFFD in their place.
See also: bytes->string, string->bytes
DecodeError
record ↑ Types
Why bytes did not decode: what bytes->string returns in an Err.
offset- The offset of the first bytes that do not decode, in the array that was given, not from start.
bytes- Those bytes: the invalid sequence, or what the decoder could not use.
encoding- The name of the encoding, as (text encodings) names it: "utf-8".
See also: bytes->string, decode-error-message
Utf8Chunk
type alias ↑ Types
A copy of some bytes, checked to be UTF-8 once, to take many strings from.
For a reader that finds its fields by looking at bytes and makes many
small strings from one buffer. bytes->string checks the bytes of
each string it makes. A chunk checks its bytes once, and a string taken
from it by utf8-chunk-substring is not checked again.
No string taken from a chunk can be invalid. The chunk owns its copy of the bytes, so nothing changes them after the check, and it takes a string only between two character boundaries in the part that is valid UTF-8. An offset that is not a boundary raises.
See also: bytes->utf8-chunk, utf8-chunk-substring, utf8-chunk-valid-end
InputPort
type alias ↑ Types
An input port: bytes, and text read from them.
The operations on ports, and the ports of files and strings, are in
(std prelude).
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: in-port, OutputPort
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: InputPort
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
Functions
sqrt
function ↑ Functions
(: sqrt (-> (double %u^2) (double %u)))
(sqrt x)
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
int->string
function ↑ Functions
(: int->string (-> int (#:radix int) (#:upper bool) string))
(int->string n #:radix 10 #:upper #f)
The text of an int, in decimal or another base, the same on every machine.
n- The number.
#:radix- The base, from 2 to 36. 10 when not given.
#:upper- Write the letter digits in upper case.
- returns
- Its digits, with an ASCII minus when negative.
- raises
System.ArgumentOutOfRangeException - When the radix is not from 2 to 36.
(int->string 255) ; "255"
(int->string 255 #:radix 16) ; "ff"
(int->string 255 #:radix 16 #:upper #t) ; "FF"
(int->string -5 #:radix 2) ; "-101"
(string-pad-left (int->string 233 #:radix 16 #:upper #t) 4 #:with #\0) ; "00E9"
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 with
the same radix.
Digits past 9 are letters: a is 10 and z is 35. A negative number is a
minus and the digits of its magnitude, not its two’s complement. No
prefix such as 0x is written.
See also: string->int, long->string, displayed
long->string
function ↑ Functions
(: long->string (-> long (#:radix int) (#:upper bool) string))
(long->string n #:radix 10 #:upper #f)
The text of a long, in decimal or another base, the same on every machine.
n- The number.
#:radix- The base, from 2 to 36. 10 when not given.
#:upper- Write the letter digits in upper case.
- returns
- Its digits, with an ASCII minus when negative.
- raises
System.ArgumentOutOfRangeException - When the radix is not from 2 to 36.
(long->string 1099511627776L #:radix 16) ; "10000000000"
As int->string, for 64 bits.
See also: int->string, string->long, 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
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
displayedgives.
An implementation of ->str is called by ->str only, not
by displayed, println or an interpolation.
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.
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.
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.
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.
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.
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:
ArrayandVec: indexed by integer.Map: indexed by key.string: indexed byStringCursor, returning achar.VecBuilder,TransientVecandTransientMap, the collectionsref-set!writes, andMutableVecandMutableMapin their own modules.
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:
- An index into a
Vecis out of bounds. - A key in a
Mapdoes not exist. - A
StringCursorhas reached the end of a string.
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).
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:
Array,VecBuilderandTransientVec: indexed by integer.TransientMap: by key, and a key that was not there is added.MutableVecandMutableMap, in(std mutable vec)and(std mutable map).
A persistent Vec or Map has no impl, because there is
nothing to write in place: ref-set and set answer a copy.
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.
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.
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
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!
option-map
function ↑ Functions
(: option-map (-> (-?-> %a %b) (Option %a) (Option %b)))
(option-map f opt)
Applies a function to the value inside a Some.
f- The function applied to the value. It may suspend.
opt- The Option.
- returns
- (Some (f v)) for (Some v), and None for None.
(option-map string-length (Some "abc")) ; (Some 3)
To chain a function that itself returns an Option, use
some->, or bind from (std monad).
See also: option-filter, option-or, result-map, some->
option-filter
function ↑ Functions
(: option-filter (-> (-?-> %a bool) (Option %a) (Option %a)))
(option-filter pred opt)
A Some whose value a predicate holds for, else None.
pred- The predicate. It may suspend.
opt- The Option.
- returns
- opt when it is (Some v) and (pred v) holds; None otherwise.
(option-filter (fun (n) (> n 0)) (Some 4)) ; (Some 4)
(option-filter (fun (n) (> n 0)) (Some -3)) ; None
See also: option-map
option-or
function ↑ Functions
(: option-or (-> (Option %a) (Option %a) (Option %a)))
(option-or opt other)
The first of two Options that is a Some.
opt- The Option tried first.
other- The Option returned when opt is None.
- returns
- opt when it is a Some, else other.
(option-or (map-try-ref local k) (map-try-ref global k))
Both arguments are evaluated, as for any call. To get a plain value
out with a default, use option-ref-or.
See also: option-ref-or, option-map
option->result
function ↑ Functions
(: option->result (-> (Option %a) %e (Result %e %a)))
(option->result opt e)
An Option as a Result, with an error for None.
opt- The Option.
e- The error for None.
- returns
- (Ok v) for (Some v), and (Err e) for None.
(option->result (map-try-ref users id) "no such user")
See also: result->option
result-map-err
function ↑ Functions
(: result-map-err (-> (-?-> %e %f) (Result %e %a) (Result %f %a)))
(result-map-err f r)
Applies a function to the value inside an Err.
f- The function applied to the error. It may suspend.
r- The Result.
- returns
- (Err (f e)) for (Err e); an Ok unchanged.
(result-map-err (fun (e) (str "config: " e)) (Err "no port")) ; (Err "config: no port")
See also: result-map, result->option
result-ref
function ↑ Functions
(: result-ref (-> (Result %e %a) %a))
(result-ref r)
The value inside an Ok.
r- The Result. Must be Ok.
- returns
- The value it holds.
- raises
System.InvalidOperationException - When r is an Err.
See also: result-ref-or, option-ref, ok?
result-ref-or
function ↑ Functions
(: result-ref-or (-> (Result %e %a) %a %a))
(result-ref-or r fallback)
Returns the value inside an Ok, or a fallback for an Err.
r- The Result.
fallback- The value to return if r is an Err. Eagerly evaluated.
- returns
- The value r holds, or fallback.
(result-ref-or (try (string->int text) #:catch (System.FormatException)) 0)
See also: result-ref, option-ref-or
result->option
function ↑ Functions
(: result->option (-> (Result %e %a) (Option %a)))
(result->option r)
A Result as an Option, without the error.
r- The Result.
- returns
- (Some v) for (Ok v), and None for an Err.
See also: option->result, ok?
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
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. When the consumer of a lazy seql
stops early, the cursors that the seql has open get one of the
two: iterable-end if the consumer was fused into the
seql’s loop, and iterable-cleanup if not. 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, unless the consumer was fused into the seql’s loop:
those cursors then get iterable-end. Each cursor gets one of the
two calls 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.
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.
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) #:when (< a b))) ; how many rise
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
->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.
->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.
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.
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.
->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.
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
contiguous?
function ↑ Functions
(: contiguous? (-> %s bool))
Whether the values of a Contiguous sequence are in one span now.
s- The sequence.
- returns
- #t when
contiguous-valuesandcontiguous-validgive all the elements. When #f, a loop walks the elements one by one.
Contiguous is a promise of the implementation: the
Iterable cursor of the type is an int that starts at 0 and steps
by 1, and the walk is done when the cursor is the length of the values.
The element at cursor i is values[i]. When the element is an
(Option %value), it is (Some values[i]) if bit i of the
valid bitmap is set, and None if it is not. A loop over Contiguous
sequences into BlockCollectors can be compiled to vector instructions.
The compiler does not prove the promise.
See also: contiguous-values, contiguous-valid, block-span
contiguous-values
function ↑ Functions
(: contiguous-values (-> %s (RoSpan %value)))
The values of a Contiguous sequence, in the order of its walk.
s- The sequence.
contiguous?answered #t for it. - returns
- The values. Under a None element the value is unspecified.
See also: contiguous?, contiguous-valid
contiguous-valid
function ↑ Functions
(: contiguous-valid (-> %s (RoSpan byte)))
The valid bitmap of a Contiguous sequence.
s- The sequence.
contiguous?answered #t for it. - returns
- Bit i of byte i/8, the least significant bit first, is set when element i is not None. Empty when no element is None.
See also: contiguous?, contiguous-values
block-count
function ↑ Functions
(: block-count (-> %c %acc int))
How many elements a BlockCollector’s accumulator has taken in.
c- The collector.
acc- The accumulator.
- returns
- The number of elements.
BlockCollector is a promise of the implementation: the
accumulator takes elements a block at a time with the same result as one
collector-step for each. The collector’s element is
%value or (Option %value).
See also: block-grow, block-span, block-none!, contiguous?
block-grow
function ↑ Functions
(: block-grow (-> %c %acc int %acc))
An accumulator with room for more elements at the end.
c- The collector.
acc- The accumulator.
n- How many elements to add.
- returns
- The accumulator with n more elements, as if taken in: not None, with values that are written next through
block-span.
See also: block-span, block-none!
block-span
function ↑ Functions
(: block-span (-> %c %acc int int (Span %value)))
Elements of a BlockCollector’s accumulator, to write.
c- The collector.
acc- The accumulator.
start- The first element.
n- How many elements.
- returns
- The elements from start, n of them.
See also: block-grow, block-none!
block-none!
function ↑ Functions
(: block-none! (-> %c %acc int void))
Makes an element of a BlockCollector’s accumulator None.
c- The collector.
acc- The accumulator.
i- The element.
See also: block-grow, block-span
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.
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. It never fails. A
Vec appends at the end. A set already holding x answers an equal
set. A Map has set semantics: a key already there takes the new
value. Where a key already there is a mistake, write map-add-new,
which raises, or map-try-add-new.
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.
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.
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, and the mutable collections,
implement it in their own modules.
It never fails. Afterwards the sink holds x: a sequence has it
appended, a set has it as a member (which it may already have been), and
a map has the key mapped to the value, replacing an older one. An
operation that refuses what is already there is named add-new,
such as mutablemap-add-new!, and is not part of the trait.
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.
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)
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)
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.
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.
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.
list-append
function ↑ Functions
(: list-append (-> (List %a) (List %a) #:rest (List %a) (List %a)))
(list-append xs ys #:rest more)
Lists joined in order: one list followed by the others.
xs- The elements that come first. They are copied.
ys- The elements that come next. Copied if more lists follow, else shared.
more ...- More lists, in order. The last one is shared, the others are copied.
- returns
- A list of xs's elements, then ys's, then those of each list in more.
(list-append (list 1 2) (list 3)) ; (1 2 3)
(list-append (list 1) (list 2) (list 3 4)) ; (1 2 3 4)
(apply list-append (list 1) (list 2) parts) ; with parts a list of lists
O(n) in the length of all lists but the last, and independent of the last: the result’s last cells are the last list itself. Each list is copied once, as the lists are joined from the right.
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-contains?
function ↑ Functions
(: list-contains? (-> (List %a) %a bool))
(list-contains? xs x)
Whether a list holds an element.
xs- The list.
x- The element to look for.
- returns
- #t when some element of xs is = to x.
Compares with =, the Eq trait, and stops at the first
match. O(n).
See also: list-filter, vec-contains?
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->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
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-contains?
function ↑ Functions
(: vec-contains? (-> (Vec %a) %a bool))
(vec-contains? v x)
Whether a vec holds an element.
v- The vec.
x- The element to look for.
- returns
- #t when some element of v is = to x.
Compares with =, the Eq trait, from the front, and stops
at the first match. O(n).
See also: vec-iter, list-contains?, transientvec-contains?
vec-add-first
function ↑ Functions
(: vec-add-first (-> (Vec %a) %a (Vec %a)))
Returns a vec with one element added at the front.
v- The persistent vector (unmodified).
x- The element to add.
- returns
- A new vec, one longer, with x first.
The persistent counterpart of transientvec-add-first!. Equivalent
to (vec-insert v 0 x).
See also: vec-add, vec-pop-first, transientvec-add-first!, vec-insert
vec-insert
function ↑ Functions
(: vec-insert (-> (Vec %a) int %a (Vec %a)))
(vec-insert v i x)
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)))
(vec-remove-at v i)
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-try-pop
function ↑ Functions
(: vec-try-pop (-> (Vec %a) (Option (Vec %a))))
(vec-try-pop v)
A vec without its last element, or None when it is empty.
v- The vec, which is left as it was.
- returns
- (Some w), where w is one shorter than v, or None when v is empty.
See also: vec-pop, vec-try-pop-first
vec-try-pop-first
function ↑ Functions
(: vec-try-pop-first (-> (Vec %a) (Option (Vec %a))))
(vec-try-pop-first v)
A vec without its first element, or None when it is empty.
v- The vec, which is left as it was.
- returns
- (Some w), where w is one shorter than v, or None when v is empty.
See also: vec-pop-first, vec-try-pop
vec-slice
function ↑ Functions
(: vec-slice (-> (Vec %a) int int (Vec %a)))
(vec-slice v start count)
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.
vec-split
function ↑ Functions
(: vec-split (-> (Vec %a) int (Tuple (Vec %a) (Vec %a))))
(vec-split v i)
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-append
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.
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) (#:from int) (#:to int) Unit))
(vec-for-each f v #:from 0 #:to (vec-length v))
Calls a function on each element of a vec, or of a run of it, for its effect.
f- Called with each element, front to back.
v- The vec.
#:from- The first index visited. 0 by default.
#:to- The index after the last one visited. The length by default.
The run is checked before f is first called. Unless
0 <= from <= to <= length, it raises
System.ArgumentOutOfRangeException.
(vec-for-each println ["a" "b" "c"]) ; a b c
(vec-for-each println ["a" "b" "c"] #:from 1) ; b c
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
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-contains?
function ↑ Functions
(: transientvec-contains? (-> (TransientVec %a) %a bool))
(transientvec-contains? t x)
Whether a transient holds an element.
t- The transient.
x- The element to look for.
- returns
- #t when some element of t is = to x.
Compares with =, the Eq trait, and stops at the first match. O(n).
See also: vec-contains?
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-try-pop!, transientvec-add!, transientvec-pop-first!
transientvec-try-pop!
function ↑ Functions
(: transientvec-try-pop! (-> (TransientVec %a) (Option %a)))
(transientvec-try-pop! t)
Removes the last element, in place, and returns it, or returns None when the transient is empty.
t- The transient.
- returns
- (Some x) for the element that was last, or None. None leaves the transient as it was.
See also: transientvec-pop!, transientvec-try-pop-first!
transientvec-try-pop-first!
function ↑ Functions
(: transientvec-try-pop-first! (-> (TransientVec %a) (Option %a)))
(transientvec-try-pop-first! t)
Removes the first element, in place, and returns it, or returns None when the transient is empty.
t- The transient.
- returns
- (Some x) for the element that was first, or None. None leaves the transient as it was.
See also: transientvec-pop-first!, transientvec-try-pop!
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-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
array-contains?
function ↑ Functions
(: array-contains? (-> (Array %a) %a bool))
(array-contains? a x)
Whether an array holds an element.
a- The array.
x- The element to look for.
- returns
- #t when some element of a is = to x.
Compares with =, the Eq trait, and stops at the first match. O(n).
See also: iarray-contains?, vec-contains?
array-copy!
function ↑ Functions
(: array-copy! (-> (Array %a) int (Array %a) int int void))
Copies a range of one array into another, or into another place in the same one.
src- The array copied from.
src-start- The first index copied.
dst- The array written. It can be src.
dst-start- Where the first element goes.
count- How many elements.
- raises
System.ArgumentException - When a range is outside its array.
(def a #[1 2 3 4 5])
(array-copy! a 0 a 1 4) ; a is #[1 1 2 3 4]
One Array.Copy: at any element type, a block copy rather than a
loop of array-ref and array-set!. Overlapping ranges in one
array are copied as if through a buffer.
See also: array-resize, make-array
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.
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.
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
iarray-empty
function ↑ Functions
(: iarray-empty (-> (IArray %a)))
An empty immutable array.
- returns
- An IArray with no elements.
See also: iarray-empty?
iarray-length
function ↑ Functions
(: iarray-length (-> (IArray %a) int))
How many elements an immutable array has.
xs- The array.
- returns
- Its number of elements. O(1).
See also: iarray-empty?
iarray-empty?
function ↑ Functions
(: iarray-empty? (-> (IArray %a) bool))
Whether an immutable array has no elements.
xs- The array.
- returns
- #t when its length is 0.
See also: iarray-length
iarray-ref
function ↑ Functions
(: iarray-ref (-> (IArray %a) int %a))
The element of an immutable array at an index.
xs- The array.
i- Zero-based index (0 <= i < length).
- returns
- The element at i. An array read.
- raises
System.IndexOutOfRangeException - When i is negative or not less than the length.
See also: iarray-try-ref, ref
iarray-try-ref
function ↑ Functions
(: iarray-try-ref (-> (IArray %a) int (out %a) (Option %a)))
The element at an index, or None if the index is out of bounds.
xs- The array.
i- Zero-based index.
- returns
- (Some x) if index i is valid, otherwise None.
See also: iarray-ref, try-ref
iarray-contains?
function ↑ Functions
(: iarray-contains? (-> (IArray %a) %a bool))
(iarray-contains? a x)
Whether an immutable array holds an element.
a- The array.
x- The element to look for.
- returns
- #t when some element of a is = to x.
Compares with =, the Eq trait, and stops at the first match. O(n).
See also: array-contains?, vec-contains?
iarray-set
function ↑ Functions
(: iarray-set (-> (IArray %a) int %a (IArray %a)))
A copy of an immutable array with the element at an index replaced.
xs- The array, which is left as it was.
i- Zero-based index (0 <= i < length).
x- The new element.
- returns
- A new array with x at i. O(n): the whole array is copied.
- raises
System.ArgumentOutOfRangeException - When i is negative or not less than the length.
See also: iarray-add, vec-set
iarray-add
function ↑ Functions
(: iarray-add (-> (IArray %a) %a (IArray %a)))
A copy of an immutable array with one element added at the end.
xs- The array, which is left as it was.
x- The element to add.
- returns
- A new array, one longer, with x last. O(n): the whole array is copied.
To build an array element by element, add to a MutableVec from
(std mutable vec) and convert it once with
mutablevec->iarray, or fill an array and use
subarray->iarray.
See also: iarray-set, vec-add
iarray-map
function ↑ Functions
(: iarray-map (-> (-> %a %b) (IArray %a) (IArray %b)))
An immutable array of the results of a function on each element.
f- The function, called on each element in order.
xs- The array.
- returns
- A new array of the same length.
See also: vec-map
subarray->iarray
function ↑ Functions
(: subarray->iarray (-> (Array %a) int int (IArray %a)))
An immutable array of part of an array.
a- The array, which the result does not share and which can be written again.
start- The first index taken, from 0.
count- How many elements are taken.
- returns
- An IArray of a[start, start + count).
- raises
System.ArgumentOutOfRangeException - When the range is not inside the array.
What a reader that collects elements on a stack uses: the stack is written again after the elements are copied out.
See also: array->iarray, subarray->vec
array->iarray
function ↑ Functions
(: array->iarray (-> (Array %a) (IArray %a)))
An immutable array of the elements of an array.
a- The array, which the result does not share.
- returns
- An IArray of the same elements.
See also: subarray->iarray, iarray->array
iarray->array
function ↑ Functions
(: iarray->array (-> (IArray %a) (Array %a)))
The elements of an immutable array in a new array.
xs- The immutable array.
- returns
- A new array, which the caller can write.
See also: array->iarray
seq->iarray
function ↑ Functions
(: seq->iarray (-> (Seq %a) (IArray %a)))
An immutable array of the elements of a sequence.
s- The sequence, walked once.
- returns
- An IArray of its elements, in order.
See also: iarray->seq, vec->iarray
iarray->seq
function ↑ Functions
(: iarray->seq (-> (IArray %a) (Seq %a)))
The elements of an immutable array as a sequence.
xs- The array.
- returns
- A sequence that walks xs in order.
See also: seq->iarray
vec->iarray
function ↑ Functions
(: vec->iarray (-> (Vec %a) (IArray %a)))
(vec->iarray v)
An immutable array of the elements of a vec.
v- The vec.
- returns
- An IArray of its elements, in order.
See also: iarray->vec, list->iarray
iarray->vec
function ↑ Functions
(: iarray->vec (-> (IArray %a) (Vec %a)))
(iarray->vec xs)
A vec of the elements of an immutable array.
xs- The array.
- returns
- A vec of its elements, in order.
See also: vec->iarray, iarray->list
list->iarray
function ↑ Functions
(: list->iarray (-> (List %a) (IArray %a)))
(list->iarray xs)
An immutable array of the elements of a list.
xs- The list.
- returns
- An IArray of its elements, in order.
See also: iarray->list, vec->iarray
iarray->list
function ↑ Functions
(: iarray->list (-> (IArray %a) (List %a)))
(iarray->list xs)
A list of the elements of an immutable array.
xs- The array.
- returns
- A list of its elements, in order.
See also: list->iarray, iarray->vec
array->span
function ↑ Functions
(: array->span (-> (Array %a) (#:from int) (#:to int) (Span %a)))
(array->span a #:from 0 #:to (array-length a))
A span over part of an array.
a- The array, which the span views and writes through.
#:from- The first element: 0 by default.
#:to- One past the last element: the length by default.
- returns
- The span, of length to minus from. Nothing is copied.
- raises
System.ArgumentOutOfRangeException - When the range is not inside the array.
See also: array->ro-span, span-slice
array->ro-span
function ↑ Functions
(: array->ro-span (-> (Array %a) (#:from int) (#:to int) (RoSpan %a)))
(array->ro-span a #:from 0 #:to (array-length a))
A read-only span over part of an array.
a- The array, which the span views.
#:from- The first element: 0 by default.
#:to- One past the last element: the length by default.
- returns
- The span, of length to minus from. Nothing is copied.
- raises
System.ArgumentOutOfRangeException - When the range is not inside the array.
See also: array->span, ro-span-slice
span->ro-span
function ↑ Functions
(: span->ro-span (-> (Span %a) (RoSpan %a)))
The same view, read-only.
s- The span.
- returns
- A read-only span of the same elements.
span->
function ↑ Functions
(: span-> (-> (Span %a) (Span %b)))
(span-> s)
The same memory as numbers of another type. The use gives the type.
s- A span of plain numbers.
- returns
- A span of the same bytes, as numbers of the type the use gives.
(def bytes (: (make-array 16) (Array byte)))
(: (Span long))
(def longs (span-> (array->span bytes)))
(span-set! longs 1 -1L)
(array-ref bytes 8) ; 255uy: the longs are the bytes
Nothing is copied: a write through one span is a write through the other. The new length is the length in bytes divided by the size of the new element.
Only plain numbers: the integers, float and
double. They have no references in them, and every bit pattern
of them is a value, so a span seen as another type can hold nothing that
is not a number. A span of decimal or bigint, which are
numbers but not plain ones, is a panic.
Whole elements. A length in bytes that is not a whole number of the new elements, as 7 bytes as longs, is a panic. Slice the span first.
The order of the bytes in a number is the machine’s, little-endian on x64 and ARM64.
See also: ro-span->, array->span, span-set!
ro-span->
function ↑ Functions
(: ro-span-> (-> (RoSpan %a) (RoSpan %b)))
(ro-span-> s)
The same read-only memory as numbers of another type. The use gives the type.
s- A read-only span of plain numbers.
- returns
- A read-only span of the same bytes, as numbers of the type the use gives.
(: (RoSpan int))
(def ints (ro-span-> (array->ro-span #[1uy 0uy 0uy 0uy 2uy 0uy 0uy 0uy])))
(ro-span-ref ints 1) ; 2
As span->, for a read-only span, and the result is read-only too.
So the bytes of a string, which are only given read-only, stay
read-only.
See also: span->, array->ro-span
span-length
function ↑ Functions
(: span-length (-> (Span %a) int))
How many elements a span has.
s- The span.
- returns
- Its length.
span-ref
function ↑ Functions
(: span-ref (-> (Span %a) int %a))
The element of a span at an index.
s- The span.
i- From 0. Less than the length.
- returns
- The element at i.
s[i], with .NET’s bounds check.
See also: span-set!, array-ref
span-set!
function ↑ Functions
(: span-set! (-> (Span %a) int %a void))
Replaces the element of a span at an index, in the array it views.
s- The span.
i- From 0. Less than the length.
x- The new element.
s[i] = x, with .NET’s bounds check.
See also: span-ref, array-set!
span-slice
function ↑ Functions
(: span-slice (-> (Span %a) (#:from int) (#:to int) (Span %a)))
(span-slice s #:from 0 #:to (span-length s))
A span over part of a span.
s- The span.
#:from- The first element: 0 by default.
#:to- One past the last element: the length by default.
- returns
- The span, of length to minus from, over the same array. Nothing is copied.
- raises
System.ArgumentOutOfRangeException - When the range is not inside the span.
span->array
function ↑ Functions
(: span->array (-> (Span %a) (Array %a)))
A new array with a copy of a span’s elements.
s- The span.
- returns
- The array, which the caller can keep and write.
ro-span-length
function ↑ Functions
(: ro-span-length (-> (RoSpan %a) int))
How many elements a read-only span has.
s- The span.
- returns
- Its length.
ro-span-ref
function ↑ Functions
(: ro-span-ref (-> (RoSpan %a) int %a))
The element of a read-only span at an index.
s- The span.
i- From 0. Less than the length.
- returns
- The element at i.
See also: span-ref
ro-span-slice
function ↑ Functions
(: ro-span-slice (-> (RoSpan %a) (#:from int) (#:to int) (RoSpan %a)))
(ro-span-slice s #:from 0 #:to (ro-span-length s))
A read-only span over part of a read-only span.
s- The span.
#:from- The first element: 0 by default.
#:to- One past the last element: the length by default.
- returns
- The span, of length to minus from. Nothing is copied.
- raises
System.ArgumentOutOfRangeException - When the range is not inside the span.
ro-span->array
function ↑ Functions
(: ro-span->array (-> (RoSpan %a) (Array %a)))
A new array with a copy of a read-only span’s elements.
s- The span.
- returns
- The array, which the caller can keep and write.
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-append
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.
map-clear
function ↑ Functions
(: map-clear (-> (Map %k %v) (Map %k %v)))
(map-clear m)
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))
(map-ref m k)
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))
(map-ref-or m k default)
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 (Option %v)))
(map-try-ref m k)
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))
(map-contains? m k)
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))
(map-length m)
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))
(map-empty? m)
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)))
(map-keys m)
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)))
(map-values m)
The values of a map.
m- The map.
- returns
- A sequence of the values, in the trie's order.
map-set
function ↑ Functions
(: map-set (-> (Map %k %v) %k %v (Map %k %v)))
(map-set m 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-new, map-set-all, ref-set
map-add-new
function ↑ Functions
(: map-add-new (-> (Map %k %v) %k %v (Map %k %v)))
(map-add-new m k v)
A map with a key that must be new 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. Use it where a key that is
already there is a mistake, so that the mistake is not lost.
add of the Addable trait never fails, and replaces, as
map-set does.
See also: map-try-add-new, map-set, add
map-try-add-new
function ↑ Functions
(: map-try-add-new (-> (Map %k %v) %k %v (Result %v (Map %k %v))))
(map-try-add-new m k v)
A map with a key that must be new added, or the value the key already has.
m- The map, which is left as it was.
k- The key.
v- Its value.
- returns
- (Ok m2), where m2 maps k to v; or (Err w) when m already maps k to w.
(match (map-try-add-new users name record)
((Ok users2) users2)
((Err taken) (raise (Taken name))))
map-add-new with the failure as a value. The Err carries
the value already there, which the lookup found anyway.
See also: map-add-new, map-set
map-set-all
function ↑ Functions
(: map-set-all (-> (Map %k %v) (Seq (Tuple %k %v)) (Map %k %v)))
(map-set-all m kvs)
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)))
(map-remove m k)
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-alter
function ↑ Functions
(: map-alter (-> (Map %k %v) %k (-?-> (Option %v) (Option %v)) (Map %k %v)))
(map-alter m k f)
A map with the entry of a key decided by a function, in one lookup.
m- The map, which is left as it was.
k- The key.
f- Called once with (Some v) for the value of k, or None when k is not there. It returns (Some v) to set k to v, or None to remove k.
- returns
- The map with k set or removed as f says. When nothing changes, m itself.
(map-alter m "k" (fun (old) (Some (+ 1 (option-ref-or old 0))))) ; a count
(map-alter m "k" (fun (old) None)) ; map-remove
One descent of the trie finds the key and writes the result. A
map-try-ref followed by a map-set or map-remove
takes two. Haskell’s Data.Map.alter is the same function.
See also: map-update, map-set, map-remove, transientmap-alter!
map-update
function ↑ Functions
(: map-update (-> (Map %k %v) %k (-?-> %v %v) (#:default (Option %v)) (Map %k %v)))
(map-update m k f #:default None)
A map with a key set to a function of its value, in one lookup.
m- The map, which is left as it was.
k- The key.
f- Called once with the value of k, or with the default. Its result is the new value.
#:default- (Some d) gives the value f is applied to when k is not there. The default is None.
- returns
- The map with k set to the value f returns.
- raises
System.Collections.Generic.KeyNotFoundException - When k is not there and no #:default is given.
(map-update m "k" (fun (n) (+ n 1)) #:default (Some 0)) ; a count
(map-update m "k" string-upcase) ; k must be there
The same contract as the update path macro: a missing key raises.
#:default makes it an insert for that key.
See also: map-alter, update, map-set, transientmap-update!
map-remove-all
function ↑ Functions
(: map-remove-all (-> (Map %k %v) (Seq %k) (Map %k %v)))
(map-remove-all m ks)
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)))
(map-merge m other)
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)))
(map-merge-with f m other)
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.
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))
(map-any? pred m)
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.
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-any?, map-filter, find
map-split
function ↑ Functions
(: map-split (-> (Map %k %v) int (Array (Map %k %v))))
(map-split m k)
Splits a map into about k maps that together hold each entry once.
m- The map to split.
k- How many parts to aim for.
- returns
- An array of at most
kmaps, or ofmalone.
The parts share the nodes of m; only the nodes above a cut are
new. Cuts follow the trie, so parts have about equal sizes when hashes
are spread, and different sizes when they are not. A part counts its
entries the first time its length is asked for. Returns m alone
when k is at most 1, m holds at most one entry, or all
keys share one hash. (std parallel) uses it to divide work.
See also: map-merge
map-cursor
function ↑ Functions
(: map-cursor (-> (Map %k %v) (MapCursor %k %v)))
(map-cursor m)
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))
(map-cursor-done? c)
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)))
(map-cursor-current c)
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)))
(map-cursor-next c)
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.
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.
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.
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.
map->seq
function ↑ Functions
(: map->seq (-> (Map %k %v) (Seq (Tuple %k %v))))
(map->seq m)
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.
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)))
(map->mapbuilder m)
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))
(mapbuilder-add! b k v)
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))
(mapbuilder-add-all! b kvs)
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))
(mapbuilder-length b)
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)))
(mapbuilder->map b)
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)))
(map->transientmap m)
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)))
(transientmap->map t)
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))
(transientmap-set! t k v)
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))
(transientmap-set-all! t kvs)
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))
(transientmap-remove! t k)
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-alter!
function ↑ Functions
(: transientmap-alter! (-> (TransientMap %k %v) %k (-?-> (Option %v) (Option %v)) void))
(transientmap-alter! t k f)
Sets or removes the entry of a key, as a function decides, in a transient map, in place.
t- The transient.
k- The key.
f- Called once with (Some v) for the value of k, or None when k is not there. It returns (Some v) to set k to v, or None to remove k.
See also: transientmap-update!, map-alter
transientmap-update!
function ↑ Functions
(: transientmap-update! (-> (TransientMap %k %v) %k (-?-> %v %v) (#:default (Option %v)) void))
(transientmap-update! t k f #:default None)
Sets a key to a function of its value in a transient map, in place.
t- The transient.
k- The key.
f- Called once with the value of k, or with the default. Its result is the new value.
#:default- (Some d) gives the value f is applied to when k is not there. The default is None.
- raises
System.Collections.Generic.KeyNotFoundException - When k is not there and no #:default is given.
See also: transientmap-alter!, map-update
transientmap-remove-all!
function ↑ Functions
(: transientmap-remove-all! (-> (TransientMap %k %v) (Seq %k) void))
(transientmap-remove-all! t ks)
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))
(transientmap-filter! keep? t)
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))
(transientmap-ref t k)
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))
(transientmap-ref-or t k default)
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 (Option %v)))
(transientmap-try-ref t k)
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))
(transientmap-contains? t k)
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-has-key?
function ↑ Functions
(: transientmap-has-key? (-> (TransientMap %k %v) %k bool))
(transientmap-has-key? m key)
Whether a transient map has a key.
m- The transient.
key- The key.
- returns
- #t when key is there.
The same as transientmap-contains?.
See also: transientmap-contains?, map-has-key?
transientmap-length
function ↑ Functions
(: transientmap-length (-> (TransientMap %k %v) int))
(transientmap-length t)
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))
(transientmap-empty? t)
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-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?
string-find
function ↑ Functions
(: string-find (-> (-> char bool) string (Option StringCursor)))
(string-find 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-find 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
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
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
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
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=?
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 (#:radix int) int))
(string->int s #:radix 10)
Parses a string into an int, in decimal or another base.
s- Digits, with an optional sign.
#:radix- The base, from 2 to 36. 10 when not given.
- returns
- The parsed integer value.
- raises
System.FormatException - When s is not a number in the radix.
- raises
System.OverflowException - When the number does not fit in an int.
- raises
System.ArgumentOutOfRangeException - When the radix is not from 2 to 36.
(string->int "-42") ; -42
(string->int "1F600" #:radix 16) ; 128512
(string->int "-101" #:radix 2) ; -5
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.
In another base, the digits past 9 are letters in either case: a is 10
and z is 35. A sign is allowed. A prefix such as 0x is not: it is
text that is not a number.
See also: string->long, string->double, int->string
string->long
function ↑ Functions
(: string->long (-> string (#:radix int) long))
(string->long s #:radix 10)
Parses a string into a long, in decimal or another base.
s- Digits, with an optional sign.
#:radix- The base, from 2 to 36. 10 when not given. See
string->int. - 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) (Result DecodeError string)))
(bytes->string bytes #:encoding clr-utf-8 #:start 0 #:end (array-length bytes))
The text some bytes encode, or why they do not.
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.
- returns
- (Ok text) of the bytes from start to end, or (Err e) with a DecodeError for the first bytes that do not decode.
- raises
System.ArgumentOutOfRangeException - When the range is not inside the array, or start is after end.
(bytes->string (string->bytes "blåbär")) ; (Ok "blåbär")
(bytes->string #[104 255 105]) ; (Err (DecodeError (offset 1) ...))
(bytes->string bs #:encoding windows-1252) ; with (text encodings)
(def (Ok text) (bytes->string bs) :leave ((Err e) (panic! (decode-error-message e))))
Strict, as Racket’s bytes->string/utf-8 is. Bytes from a file, a
socket or another program are not known to decode, so the result is a
Result: the caller says what a failure means. Use
bytes->string/lossy where a replacement character is the right
answer.
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 raises, because that is a mistake of the caller, not of the bytes.
See also: bytes->string/lossy, DecodeError, string->bytes, Encoding
bytes->string/lossy
function ↑ Functions
(: bytes->string/lossy (-> (Array byte) (#:encoding Encoding) (#:start int) (#:end int) (#:replace char) string))
(bytes->string/lossy bytes #:encoding clr-utf-8 #:start 0 #:end (array-length bytes) #:replace #\xFFFD)
The text some bytes encode, with a replacement for each sequence that does not decode.
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- What goes in place of each sequence that does not decode: U+FFFD by default.
- returns
- The text. It never fails on the bytes.
- raises
System.ArgumentOutOfRangeException - When the range is not inside the array, or start is after end.
- raises
System.ArgumentException - When the encoding has no way to show the replacement.
(bytes->string/lossy #[104 255 105]) ; "h\u{FFFD}i"
(bytes->string/lossy #[104 255 105] #:replace #\?) ; "h?i"
From UTF-8, a sequence that does not decode is the longest start of a valid one, or one byte, by the rule of Unicode chapter 3.
See also: bytes->string
decode-error-message
function ↑ Functions
(: decode-error-message (-> DecodeError string))
(decode-error-message e)
A DecodeError as a sentence.
e- The error.
- returns
- Text such as "the bytes at offset 1 (0xFF) are not valid utf-8".
See also: DecodeError
bytes-utf-8?
function ↑ Functions
(: bytes-utf-8? (-> (Array byte) int int bool))
Whether a range of bytes is UTF-8.
bytes- The array.
start- The first byte checked.
end- Where the range ends, not included.
- returns
- #t when the bytes are whole UTF-8 characters, with no overlong form, no surrogate and nothing past U+10FFFF: what bytes->string accepts.
- raises
System.ArgumentOutOfRangeException - When the range is not inside the array.
One vectorized pass. A reader that copies runs of bytes into a string builder checks each run with it, and looks at the bytes one by one only when a run is not UTF-8, to say where.
See also: bytes->string, string->bytes
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
bytes->utf8-chunk
function ↑ Functions
(: bytes->utf8-chunk (-> (Array byte) (#:start int) (#:end int) Utf8Chunk))
(bytes->utf8-chunk bytes #:start 0 #:end (array-length bytes))
A chunk of a copy of some bytes.
bytes- The bytes.
#:start- The first byte to copy: 0 by default.
#:end- One past the last byte to copy: the end of the array by default.
- returns
- The chunk. Its offsets count from start.
- raises
System.ArgumentOutOfRangeException - When the range is not inside the array.
(def c (bytes->utf8-chunk (string->bytes "blåbär,öl")))
(utf8-chunk-substring c 0 8) ; "blåbär"
(utf8-chunk-substring c 9 12) ; "öl"
(utf8-chunk-substring c 0 3) ; raises: 3 is inside the å
Bytes that are not valid UTF-8 are not an error here. The chunk is
valid up to utf8-chunk-valid-end, and strings are taken only
from that part. A buffer read from a port is often cut inside its last
character, and is then valid up to that character.
See also: utf8-chunk-substring, utf8-chunk-valid-end
utf8-chunk-length
function ↑ Functions
(: utf8-chunk-length (-> Utf8Chunk int))
How many bytes a chunk has.
c- The chunk.
- returns
- The number of bytes copied into it.
See also: utf8-chunk-valid-end
utf8-chunk-valid-end
function ↑ Functions
(: utf8-chunk-valid-end (-> Utf8Chunk int))
Where the valid UTF-8 at the start of a chunk ends.
c- The chunk.
- returns
- Its length when all of it is UTF-8. Else the offset of the first sequence that is not valid, or not whole. Always between two characters.
See also: utf8-chunk-substring
utf8-chunk-substring
function ↑ Functions
(: utf8-chunk-substring (-> Utf8Chunk int int string))
The text between two byte offsets of a chunk, not checked again.
c- The chunk.
start- The offset of the first byte.
end- The offset after the last byte, not before start.
- returns
- A string with bytes of its own.
- raises
System.ArgumentOutOfRangeException - When the range is not inside the valid part, or start is after end.
- raises
System.ArgumentException - When start or end is inside a character.
Checking the two offsets is two byte tests. A range cut out of valid UTF-8 between characters is itself valid, so the bytes are copied and not checked.
See also: bytes->utf8-chunk, bytes->string
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=?
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<?
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.
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.
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.
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.
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
Values
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.
int-min
value ↑ Values
The smallest int, -2147483648.
System.Int32.MinValue, down-from’s default #:to.
Macros
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, inthenonly. expr- An expression evaluating to an Option. Evaluated once.
then- Expression evaluated when
expris(Some ...). else- Expression evaluated when
exprisNone.
(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)).
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).
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
lettakes 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
parameterizetakes 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*
type/derive
macro ↑ Macros
(type/derive (trait ...) typedef ...)
Declares types and writes their implementations from the declaration.
trait ...EqorOrdfor a record, a struct or a union; any trait for a newtype.typedef ...- A type declaration as
typetakes 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.
finding
macro ↑ Macros
(finding x)
An accumulator of the first value a loop reaches it with, which ends the loop: (Some x), or None.
x- The value to find. Evaluated once, in the first round that reaches the accumulator.
{finding x (:for x xs) (:when (even? x))} ; the first even element, or None
{finding (* x x) :when (> x 3) (:for x xs)} ; the square of the first above 3
(loop (:for (Tuple i x) (enumerate xs))
(:acc at (finding i) #:when (= x 0))
=> at) ; where the first 0 is
Written (:acc name (finding x)) in a loop, and
{finding x clause ...} as a comprehension. Its value is
(Some x) for the first round that reaches it, or None when
the loop ends before one does.
A collector macro, def/acc-clause: it is
(someing (Some x)), so the round that finds ends the loop, and
the clauses after it in that round do not run. With #:when, the
condition is evaluated once and gates both.
someing
macro ↑ Macros
(someing expr)
An accumulator of the first (Some v) an Option expression evaluates to, which ends the loop, or None.
expr- An Option. Evaluated once a round.
{someing (map-try-ref ages n) (:for n names)} ; the age of the first name in ages, or None
Written (:acc name (someing expr)) in a loop, and
{someing expr clause ...} as a comprehension. Its value is the
(Some v) as expr gave it, not wrapped again, or
None when every round gave None.
finding is the case where every round that reaches it gives a
value: (finding x) is (someing (Some x)).
A collector macro: it returns a folding of expr and a
(:finish ...) after it, so the round that gives a Some is
the last, and the clauses after it in that round do not run. With
#:when, the rounds the condition does not hold for do not
evaluate expr.
anding
macro ↑ Macros
(anding test)
An accumulator of whether a test holds in every round. The first round it does not hold in ends the loop.
test- A bool. Evaluated once a round.
{anding (> x 0) (:for x xs)} ; whether every element is positive
(loop (:for x xs)
(:acc ok (anding (even? x)) #:when (> x 0))
=> ok) ; whether every positive element is even
Written (:acc name (anding test)) in a loop, and
{anding test clause ...} as a comprehension. It is #t for
a loop of no rounds.
A collector macro: it returns a folding of the test and a
(:finish ...) after it, so the round whose test fails is the last.
With #:when, the rounds the condition does not hold for are not
tested.
oring
macro ↑ Macros
(oring test)
An accumulator of whether a test holds in some round. The first round it holds in ends the loop.
test- A bool. Evaluated once a round.
{oring (string-empty? s) (:for s lines)} ; whether any line is empty
Written (:acc name (oring test)) in a loop, and
{oring test clause ...} as a comprehension. It is #f for a
loop of no rounds.
A collector macro: it returns a folding of the test and a
(:finish ...) after it, so the round whose test holds is the last.
With #:when, the rounds the condition does not hold for are not
tested. Use finding for the value that held.
taking
macro ↑ Macros
(taking n x)
An accumulator of a list of the first n values. The round that takes the nth ends the loop.
n- How many to take, an int. Evaluated once a round.
x- The value to take.
{taking 3 x (:for x xs) (:when (prime? x))} ; the first three primes in xs
Written (:acc name (taking n x)) in a loop, and
{taking n x clause ...} as a comprehension. The list is in the
order taken, and shorter than n when the loop ends first.
For a sequence, (:for x (take n xs)) does the same.
taking is for counting only the rounds that reach it, after a
:when or with #:when.
A collector macro: it returns a listing that takes a value only
while it holds fewer than n, and a (:finish ...) after it.
An n of 0 or less takes nothing, but the loop still runs its
first round.
maximizing-by
macro ↑ Macros
(maximizing-by key x)
An accumulator of the value with the greatest key: (Some x), or None for no rounds.
key- The key to compare, by Ord. Evaluated once a round.
x- The value kept for the key.
{maximizing-by (string-length w) w (:for w words)} ; the longest word
Of equal keys the first is kept. A collector macro: it is the
collector (maximizing/pairs (Tuple key x)).
See also: minimizing-by, Maximizing, MaximizingPairs
minimizing-by
macro ↑ Macros
(minimizing-by key x)
An accumulator of the value with the least key: (Some x), or None for no rounds.
key- The key to compare, by Ord. Evaluated once a round.
x- The value kept for the key.
{minimizing-by (abs (- x target)) x (:for x xs)} ; the one nearest target
Of equal keys the first is kept. A collector macro: it is the
collector (minimizing/pairs (Tuple key x)).
See also: maximizing-by, Minimizing, MinimizingPairs
grouping
macro ↑ Macros
(grouping key x)
An accumulator of a map from each key to the list of its values, in the order they came.
key- The key to group by, by Eq. Evaluated once a round.
x- The value put in the key's list.
{grouping (string-length w) w (:for w words)} ; the words of each length
A collector macro: it is the collector
(grouping/pairs (Tuple key x)).
See also: Tallying, GroupingPairs, Mapping
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.
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:
.namefor 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.
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:
.namefor 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.
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:
.namefor 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.
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.
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.