Overview
What every module has access to without importing anything: collections, strings, files, ports, concurrency and the macros the language is written with.
(defun (main)
(def words (string-split (file-read-text "notes.txt") " "))
(println #"(length words) words")
0)
Every module outside the standard library imports (std prelude)
without saying so, unless it imports it itself, with modifiers, to hide or
rename part of it. Its forms come from these
places: the definitions in std/prelude.bjo, all of
(std prelude core), (std prelude bytestring) and
(std prelude path), which it re-exports, the names it re-exports
from (std eq) and (std maths), and the builtins compiled
into the runtime. The docs of a re-exported name are in the module that
defines it. The builtins are documented here.
Collections. List is the immutable linked list,
Vec the persistent vector (an rrb tree), Map the persistent hash map (a champ), and
.NET arrays are there for interop and speed. Each has functions of its
own, named after it (list-map, vec-ref, map-set),
and a builder or a transient for building one in a loop.
Iteration. The traits Iterable, Collection,
Cursor and Collector are what loop and the generic
fold, map, filter and length work through, so
those work on every collection, on strings, on ranges and on lazy
Seqs.
Strings and characters. A string is UTF-8, and positions in one
are cursors rather than indices. A char is a Unicode scalar value.
A ByteString is bytes with no encoding, and positions in one are
offsets.
Files and ports. Files are read and written whole, or through
ports. A function that takes a path takes a string, a
ByteString or a Path: any value of AsPath. The file
system is reached through the FS effect, so it can be mocked. The
operations of the effect take a Path. Logging is reached through
the warn and log effects.
Concurrency. Bjoroutines run on fibers, which meet on channels
through Concurrent ML events (sync, choose, wrap),
inside scopes that wait for them, cancel them, and raise their failures
(with-scope, with-deadline).
Macros. cond, if-let, some->, get,
type/derive and the reader extensions #map and #ch are
macros, and the syntax functions macro transformers use are here as well.
See also: println, displayed, fold, map, list-map, vec-map, map-ref, str, file-read-text, read-line, sync, with-scope, cond
Reference
%*+-/<<=>>=alwaysarray->vecarray-lengtharray-refarray-resizearray-set!async-seq->chanbitwise-andbitwise-iorbitwise-notbitwise-xorblockingcall-with-dynamic-environmentcall-with-input-filecall-with-output-filecancel-reasoncancelledcancelled?chan-getchan-putchan-recvchan-sendchar->intchar->stringchooseclose-input-portclose-output-portclose-owned-or-disposeclr-eqclr-equalsclr-hashclr-string->stringConsconscurrent-directorycurrent-dynamic-environmentcurrent-scopedetachdirectory-createdirectory-deletedirectory-delete-treedirectory-exists?directory-filesdirectory-subdirectoriesdirectory-walkdisplaydisplaylnduration->timer-msduration-ticksdyn-restore!eq-comparereq?ErrFailedfiber-tracefile-append-bytesfile-append-textfile-copyfile-deletefile-exists?file-infofile-movefile-read-bytesfile-read-linesfile-read-lines/seqfile-read-textfile-read/seqfile-write-bytesfile-write-linesfile-write-textflush-portfs-create-directoryfs-create-directory/rawfs-delete-directoryfs-delete-directory/rawfs-delete-filefs-delete-file/rawfs-infofs-info/rawfs-listfs-list/rawfs-movefs-move/rawget-environment-variableget-output-bytesget-output-stringgetenvguardhash-combinehoursint->charkeyword->stringkeyword?link-cancellistlist->builderlist->listbuilderlist->seqlist-emptylist-empty?list-headlist-lengthlist-reflist-reverselist-taillistbuilder->listlistbuilder-add!listbuilder-add-range!listbuilder-emptylistbuilder-lengthlogmake-arraymake-cancelmake-chanmake-clockmake-cold-parametermake-parametermillisecondsminutesmonotonic-msmonotonic-nsnegatenevernewlinenone?Okopen-input-fileopen-input-file/rawopen-input-stringopen-output-fileopen-output-file/rawopen-output-stringopen-read-streamopen-read-stream/rawopen-write-streamopen-write-stream/rawoption-refoption-ref-orord-comparerown!parameter-push!parameter-refpath-absolutepath-combinepath-directorypath-file-extensionpath-filenamepeek-charpeek-char/optport-eof?port-foldpromise-done?promise-joinpromise-join/syncraiseread-allread-charread-char/optread-lineread-line/optreader->listreader->vecreader-read-char!reader-read-line!reciprelease!RequestedSCharscope-cancel!scope-cancellerscope-close!scope-close!/blockingscope-open!scope-owned-countscope-push!scope-tokenSDatumsecondsseq->listseq->vecseq-appendseq-dropseq-emptyseq-empty?seq-enumeratorseq-enumerator-currentseq-enumerator-end!seq-enumerator-next!seq-filterseq-headseq-lengthseq-mapseq-rangeseq-takeseq-unfoldset-current-directory!set-environment-variable!shield-open!shift-leftshift-rightshift-right-logicalSIntSKeySListSomesome?spawn-evt/startspawn-thunkspawn/threadSPunctSStrSSymstring->clr-stringstring->keywordstring->symbolstring-countstring-cursor-endstring-cursor-end?string-cursor-nextstring-cursor-prevstring-cursor-refstring-cursor-ref+nextstring-cursor-startstring-empty?string-searchstring-search-anystring-search-backwardstringbuilder->stringstringbuilder-add!stringbuilder-add-byte!stringbuilder-add-bytes!stringbuilder-add-double!stringbuilder-add-long!stringbuilder-add-string!stringbuilder-add-substring!stringbuilder-add-unit!stringbuilder-byte-refstringbuilder-clear!stringbuilder-emptystringbuilder-lengthstringbuilder=?structural-equalsstructural-hashsubarray->vecsubstringsubstring/slicesymbol->stringsymbol?syncsync/blockingsyntax->stringsyntax-atsyntax-errorsyntax-filesyntax-ident=?syntax-linesyntax-resolvedsyntax-spliceticks->durationtimeoutunhashableuntil-cancelledvec->seqvec->vecbuildervec-appendvec-compactvec-cursorvec-cursor-currentvec-cursor-done?vec-cursor-nextvec-cursor-slicevec-emptyvec-empty?vec-lengthvec-popvec-pop-firstvec-refvec-setvecbuilder->vecvecbuilder-add!vecbuilder-emptyvecbuilder-empty/smallvecbuilder-lengthvecbuilder-refvecbuilder-set!warnwith-nackwrapwrite-charwrite-stringwritelnwriter->stringwriter-write-char!
current-cancelcurrent-clockcurrent-error-portcurrent-input-portcurrent-output-portcurrently-in-replDeadlineNilNoneop/fs-create-directoryop/fs-delete-directoryop/fs-delete-fileop/fs-infoop/fs-listop/fs-moveop/getenvop/logop/open-read-streamop/open-write-streamop/warnScope-Endedsystem-clockunit
Types
FsKind
union ↑ Types
What a path names, when it names anything.
FsFile- A file.
FsDirectory- A directory.
FsLink- A symbolic link, not followed. Only a listing reports one.
FsOther- A FIFO, a socket or a device. Only a listing reports one.
fs-info follows a symbolic link, so its kind is
FsFile or FsDirectory, and link? says whether the
path is a link. It reports a FIFO, a socket or a device as
FsFile, as .NET does.
FsEntry
record ↑ Types
One entry of a directory, as fs-list returns it.
entry-path- The directory joined with the name.
entry-name- The name, as the bytes the OS gave.
entry-kind- The entry's own kind. A symbolic link is FsLink, and is not followed.
The kind comes with the listing, so that a caller that only needs to
know which entries are directories does not ask about each one. Ask
fs-info for a link, to follow it, or for the size and the time.
The fields have the entry- prefix because the prelude’s field
names are visible everywhere.
FsInfo
record ↑ Types
Metadata returned by fs-info describing an existing path.
kind- A file or a directory.
size- In bytes. 0 for a directory.
modified-ms- The last write, in Unix milliseconds, UTC.
link?- Whether the path itself is a symbolic link.
Bundles all file attributes together to ensure atomic metadata queries.
For a link, size and modified-ms are those of what it leads
to, and a link to nothing keeps its own. directory-walk and
directory-delete-tree do not enter a directory that is a link.
Milliseconds because (std datetime)’s
unix-milliseconds->instant takes them, and the prelude cannot name
an Instant itself.
MoveMode
union ↑ Types
What a move does when something is already at the target.
MoveNew- Fails, and changes nothing.
MoveReplace- A file at the target is replaced, in the one rename that moves the new one there.
With MoveReplace nothing ever sees the target missing. A directory
is never replaced, whichever of the two it is.
WriteMode
union ↑ Types
How an output file is opened.
Truncate- Create the file, or empty it if it exists. The default.
Append- Create the file, or write after what it holds.
CreateNew- Create the file, and fail with an
IOExceptionif it exists. The check and the create are one system call, so of two writers racing for a path exactly one wins.
See also: open-output-file, call-with-output-file, open-write-stream
LineMode
union ↑ Types
What ends a line: Racket’s read-line modes.
Any- \n, \r or \r\n, the longest that matches. The default.
AnyOne- \n or \r, each on its own, so \r\n ends a line and then an empty one.
Linefeed- \n alone. A \r is part of the line.
Return- \r alone. A \n is part of the line.
ReturnLinefeed- \r\n alone. A \r or \n on its own is part of the line.
See also: read-line, read-line/opt, file-read-lines
DynamicEnvironment
type alias ↑ Types
A dynamic environment taken from where it was made: ports, parameters, cancellation token and scope.
Opaque: it can only be taken with current-dynamic-environment,
kept, sent, and given to call-with-dynamic-environment. It is what
a spawned child starts with, so it can go to another thread, and two
threads can use it at once.
See also: current-dynamic-environment, call-with-dynamic-environment
Duration
record ↑ Types
A fixed length of time: hours, minutes and seconds, not calendar days.
(with-deadline (seconds 5) (fetch url))
(displayed (minutes 90)) ;; "PT1H30M"
What every timer takes: timeout, with-deadline and
with-shield. A number of milliseconds has its unit in no type, so
5000 is easy to misread, and a count that overflows becomes a
different deadline without a word. A duration has its unit, and making
one past its range raises.
Built on TimeSpan, and holds ±(263 − 1) ticks of 100 ns,
about ±29 227 years. Ordered, and printed in ISO 8601: PT1H30M,
-PT0.5S. (std datetime) adds the arithmetic and the calendar:
duration, +duration, duration-between,
iso8601->duration. A day there is exactly 24 hours; a calendar
day is a DatePeriod.
A timer counts whole milliseconds. A part of a millisecond counts as a whole one, so a positive duration never reads as zero.
See also: seconds, timeout, with-deadline
Clock
record ↑ Types
Where the time comes from: a record of functions, so a program can make its own.
read-monotonic-ms- Milliseconds from an unspecified start. Never decreases; only differences mean anything.
read-monotonic-ns- The same clock in nanoseconds, at the resolution the clock has.
read-utc-ticks- The wall clock, in .NET ticks since 0001-01-01 UTC. May step back when the machine's time is corrected.
read-zone- The zone
(std datetime)'stodayis in. advance-ticks- What
(std datetime)'sclock-advance!calls, with a number of ticks.Nonefor a clock that cannot be moved.
monotonic-ms and monotonic-ns read current-clock, and
(std datetime)’s now and today read the same one, so
binding it moves both.
See also: make-clock, current-clock, monotonic-ms, monotonic-ns
Functions
+
function ↑ Functions
(: + (-> (num %a %u) (num %a %u) (num %a %u)))
The sum of two numbers.
a- The first addend.
b- The second, of the same type.
- returns
- a plus b. An integer sum that overflows wraps.
(+ 1 2) ; 3
#fl(+ 1 2 3) ; 6, folded from the left
(+) ; 0
The C# operator, at any type with a Num implementation. Written
with more than two operands it folds from the left; (+ x) is
x and (+) is 0.
Nothing checks for overflow at run time: (+ n 1) at
int 2147483647 is -2147483648. Widen first where a sum must not
overflow. There is no implicit widening between variables, so an
int and a double need a cast to be added.
-
function ↑ Functions
(: - (-> (num %a %u) (num %a %u) (num %a %u)))
The difference of two numbers.
a- What to subtract from.
b- What to subtract, of the same type.
- returns
- a minus b. An integer difference that overflows wraps.
(- 10 3) ; 7
#fl(- 10 3 2) ; 5, folded from the left
(- 4) ; -4, which is (negate 4)
The C# operator. With more than two operands it folds from the left. With
one, it is negate, which keeps the operand’s type.
*
function ↑ Functions
(: * (-> (num %a %u) (num %a %v) (num %a %u %v)))
The product of two numbers.
a- The first factor.
b- The second, of the same type.
- returns
- a times b. An integer product that overflows wraps.
(* 6 7) ; 42
#fl(* 2 3 4) ; 24
(*) ; 1
The C# operator. With more than two operands it folds from the left;
(* x) is x and (*) is 1.
/
function ↑ Functions
(: / (-> (num %a %u) (num %a %v) (num %a %u/%v)))
The quotient of two numbers, truncated at an integer type.
a- The dividend.
b- The divisor, of the same type.
- returns
- a divided by b, rounded toward zero for integers.
- raises
System.DivideByZeroException - When b is an integer zero.
(/ 7 2) ; 3
(/ 7.0 2.0) ; 3.5
(/ 1.0 0.0) ; infinity
#fl(/ 100 5 2) ; 10
The C# operator. Integer division truncates and throws on a zero
divisor; a constant integer divided by the literal 0 is refused at
compile time. Double division by zero is infinite, and
(/ 0.0 0.0) is NaN.
With more than two operands it folds from the left. With one, it is
recip.
%
function ↑ Functions
(: % (-> (num %a %u) (num %a %u) (num %a %u)))
The remainder of a division, with the sign of the dividend.
a- The dividend.
b- The divisor, of the same type.
- returns
- What is left of a after dividing by b.
- raises
System.DivideByZeroException - When b is an integer zero.
(% 7 2) ; 1
(% -7 2) ; -1, not 1
(% 7 -2) ; 1
The C# operator: a remainder, not a modulus. The always-positive one is
(% (+ (% a n) n) n).
See also: /
negate
function ↑ Functions
(: negate (-> (num %a %u) (num %a %u)))
A number with its sign flipped.
x- The number.
- returns
- Minus x, of x's own type.
(negate x) is the same as (- x), since (- x) expands to thi function.
A primitive rather than (- 0 x), which would fix the type to that of the literal 0 and so
refuse a double. It is C#’s unary minus, so negating the most
negative integer of a type wraps to itself.
recip
function ↑ Functions
(: recip (-> (num %a %u) (num %a 1/%u)))
The reciprocal of a number: one divided by it.
x- The number.
- returns
- 1 divided by x, of x's own type.
(recip 4.0) ; 0.25
(/ 4.0) ; the same
(recip 4) ; 0: integer division
What (/ x) expands to, emitted as 1 / x at x’s type. At
an integer type that is integer division, so it is 0 for any x other
than 1 and -1, and throws System.DivideByZeroException for 0.
<
function ↑ Functions
(: < (-> %a %a bool))
Whether one number is less than another.
a- The first operand.
b- The second, of the same type.
- returns
- #t when a is less than b. #f when either is NaN.
(< 1 2) ; #t
#ch(< 1 2 3) ; #t: each is less than the next
The C# operator, at numbers, char and StringCursor: the
types with an Ordered implementation. Not at string, which
has no such operator; compare and less? order every
comparable type, strings ordinally.
For chaining, use the #ch(< 1 2 3) hash extension, comparing each operand with the next. Comparisons follow IEEE, so one against NaN is #f whichever way round it is written.
<=
function ↑ Functions
(: <= (-> %a %a bool))
Whether one number is less than or equal to another.
a- The first operand.
b- The second, of the same type.
- returns
- #t when a is at most b. #f when either is NaN.
The C# operator, as < is. With more than two operands it chains.
>
function ↑ Functions
(: > (-> %a %a bool))
Whether one number is greater than another.
a- The first operand.
b- The second, of the same type.
- returns
- #t when a is greater than b. #f when either is NaN.
The C# operator, as < is.
>=
function ↑ Functions
(: >= (-> %a %a bool))
Whether one number is greater than or equal to another.
a- The first operand.
b- The second, of the same type.
- returns
- #t when a is at least b. #f when either is NaN.
The C# operator, as < is.
bitwise-and
function ↑ Functions
(: bitwise-and (-> %a %a %a))
The bits set in both of two integers.
a- The first integer.
b- The second, of the same type.
- returns
- a AND b, bit by bit.
(bitwise-and 12 10) ; 8
C#’s &, at every integer type, signed and unsigned: the types with
an Integral implementation. With more than two operands it folds
from the left.
See also: bitwise-ior, bitwise-xor, bitwise-not
bitwise-ior
function ↑ Functions
(: bitwise-ior (-> %a %a %a))
The bits set in either of two integers.
a- The first integer.
b- The second, of the same type.
- returns
- a OR b, bit by bit.
(bitwise-ior 12 10) ; 14
C#’s |, at every integer type.
See also: bitwise-and, bitwise-xor
bitwise-xor
function ↑ Functions
(: bitwise-xor (-> %a %a %a))
The bits set in exactly one of two integers.
a- The first integer.
b- The second, of the same type.
- returns
- a XOR b, bit by bit.
(bitwise-xor 12 10) ; 6
C#’s ^, at every integer type.
See also: bitwise-and, bitwise-ior
bitwise-not
function ↑ Functions
(: bitwise-not (-> %a %a))
An integer with every bit flipped.
x- The integer.
- returns
- The complement of x, of x's type.
(bitwise-not 0) ; -1
C#’s ~, at every integer type.
See also: bitwise-and, bitwise-xor
shift-left
function ↑ Functions
(: shift-left (-> %a int %a))
An integer’s bits moved toward the high end.
x- The integer to shift.
n- How many places. An int whatever x is, masked to x's width.
- returns
- x shifted left by n, zeroes filling in from the low end.
(shift-left 1 4) ; 16
(shift-left 1 32) ; 1, not 0: the count is masked
C#’s <<. C# masks the count to the operand’s width, so at an
int a count of 32 shifts by 0.
See also: shift-right, shift-right-logical
shift-right
function ↑ Functions
(: shift-right (-> %a int %a))
An integer’s bits moved toward the low end, keeping the sign of a signed type.
x- The integer to shift.
n- How many places. An int whatever x is, masked to x's width.
- returns
- x shifted right by n.
(shift-right -16 2) ; -4
C#’s >>: arithmetic on a signed type, copying the sign bit in,
and logical on an unsigned one. The count is masked as for
shift-left.
See also: shift-right-logical, shift-left
shift-right-logical
function ↑ Functions
(: shift-right-logical (-> %a int %a))
An integer’s bits moved toward the low end, zeroes filling in.
x- The integer to shift.
n- How many places. An int whatever x is, masked to x's width.
- returns
- x shifted right by n, with zeroes in the high bits whatever x's sign.
(shift-right-logical -1 28) ; 15
C#’s >>>. The count is masked as for shift-left.
See also: shift-right, shift-left
clr-string->string
function ↑ Functions
(: clr-string->string (-> System.String string))
A Bjolang string from a .NET System.String.
s- The .NET string. Null is allowed.
- returns
- The same text as a Bjolang string; the empty string for null.
A .NET member that takes or returns a System.String directly is
converted at the call. This is for one nested in another type, such as
a (Seq System.String).
See also: string->clr-string
Some
function ↑ Functions
(: Some (-> %a (Option %a)))
An Option holding a value.
v- The value.
- returns
- (Some v).
A case of the builtin Option, which marks presence or absence.
It is a struct, so building one does not allocate.
See also: None, some?, option-ref, option-ref-or
some?
function ↑ Functions
(: some? (-> (Option %a) bool))
Whether an Option holds a value.
opt- The Option.
- returns
- #t for Some, #f for None.
See also: none?, option-ref
none?
function ↑ Functions
(: none? (-> (Option %a) bool))
Whether an Option is None.
opt- The Option.
- returns
- #t for None, #f for Some.
See also: some?
option-ref
function ↑ Functions
(: option-ref (-> (Option %a) %a))
The value inside a Some.
opt- The Option. Must be Some.
- returns
- The value it holds.
- raises
System.InvalidOperationException - When opt is None.
See also: option-ref-or, result-ref, some?
option-ref-or
function ↑ Functions
(: option-ref-or (-> (Option %a) %a %a))
Returns the value inside an Option, or a fallback default for None.
opt- The Option.
fallback- The default value to return if opt is None. Eagerly evaluated.
- returns
- The value opt holds, or fallback.
(option-ref-or (map-try-ref settings "port") 8080)
See also: option-ref, result-ref-or
Ok
function ↑ Functions
(: Ok (-> %a (Result %e %a)))
A Result representing a successful computation.
v- The success value.
- returns
- (Ok v).
A constructor of the builtin (Result %e %a) type representing a
successful value. Every #:exceptions interop call returns a Result.
A module declaring its own Result type gets its own Ok
and Err, which shadow these.
Like any value, a Result must be explicitly used: matched, propagated,
or discarded with ignore.
See also: Err, ok?, result-map
Err
function ↑ Functions
(: Err (-> %e (Result %e %a)))
A Result representing a failure, holding an error value.
e- The error value.
- returns
- (Err e).
(match (open-input-file path)
((Ok port) (read-all port))
((Err e) (raise e)))
make-parameter
function ↑ Functions
(: make-parameter (-> %a (Param %a)))
A new parameter: a value that parameterize rebinds for a dynamic extent.
v- Its value where nothing has bound it.
- returns
- A parameter, read with parameter-ref.
(: verbose? (Param bool))
(def verbose? (make-parameter #f))
(parameterize ((verbose? #t))
(parameter-ref verbose?)) ; #t
A parameter is a value, not a function: it is read with
parameter-ref, so (Param %a) is an ordinary type that can
be passed, stored and returned.
The first 31 parameters made with make-parameter are cheap to read
however many others exist. The count is shared by the whole program,
the libraries it uses included: the prelude’s own effect operations take
some of the 31. Past that, make-parameter makes a cold one, as
make-cold-parameter does.
See also: parameter-ref, make-cold-parameter, deref
make-cold-parameter
function ↑ Functions
(: make-cold-parameter (-> %a (Param %a)))
A new parameter that gives up the cheapest kind of read.
v- Its value where nothing has bound it.
- returns
- A parameter, the same as make-parameter's in every other way.
For a parameter that is not read in a loop, so that it does not spend one of the 31 ids that stay cheap to read. Worth it for a parameter made per request or per connection rather than once at module level. Reading one costs nothing extra while it is the only cold parameter bound, and one more node access after that.
See also: make-parameter
parameter-ref
function ↑ Functions
(: parameter-ref (-> (Param %a) %a))
A parameter’s value where it is read.
p- The parameter.
- returns
- What the innermost parameterize bound it to, or its initial value.
(writeln (parameter-ref current-error-port) "failed")
See also: make-parameter, deref
parameter-push!
function ↑ Functions
(: parameter-push! (-> (Param %a) %a DynEnv))
Binds a parameter in the current dynamic environment; half of what parameterize expands to.
p- The parameter.
v- Its new value.
- returns
- The environment it displaced, for dyn-restore! to put back.
parameterize expands into a push, the body evaluation, and a
dyn-restore! of the previous environment in a finally block.
Not intended to be called directly.
See also: dyn-restore!, parameter-ref
eq?
function ↑ Functions
(: eq? (-> %a %a bool))
Whether two values are the same object.
a- The first.
b- The second.
- returns
- #t when a and b are one object; on a value type, when they are equal.
Object identity, for mutable cells, and not a substitute for =.
A value type has no identity to ask about, so on one it compares as
.NET’s default equality does. Keywords and symbols are interned, so on
them it agrees with =.
See also: =, structural-equals
clr-eq
function ↑ Functions
(: clr-eq (-> %a %a bool))
C#’s == operator, private to std/eq.
a- The first.
b- The second.
- returns
- a == b.
What (std eq)’s Eq implementations for the primitive types
are written with, so that = on them compiles to the operator.
Refused in any module but std/eq: a type’s own Eq
implementation is what .NET equality is made of, and writing one in
terms of the other is a loop. Use =, or
structural-equals.
See also: clr-equals, =
clr-equals
function ↑ Functions
(: clr-equals (-> %a %a bool))
.NET’s default equality, private to std/eq.
a- The first.
b- The second.
- returns
- The boolean result of EqualityComparer's Default.Equals.
Unlike clr-eq it compiles at a type variable, and it is reflexive
on NaN, which is why the double implementation of = uses
it. Refused in any module but std/eq, as clr-eq is.
See also: clr-eq, clr-hash, structural-equals
clr-hash
function ↑ Functions
(: clr-hash (-> %a int))
.NET’s default hash, private to std/eq.
a- The value.
- returns
- Its hash from EqualityComparer's Default; 0 for null.
The hash that goes with clr-equals, read through the same
comparer. Refused in any module but std/eq.
See also: clr-equals, structural-hash
structural-equals
function ↑ Functions
(: structural-equals (-> %a %a bool))
Field-by-field equality, without the type’s own Eq.
a- The first.
b- The second.
- returns
- #t when both are of the same runtime type and every field is equal.
(impl (Eq Point)
(defun (= a b) (structural-equals a b))
(defun (eq-hash p) (structural-hash p)))
For an Eq implementation that wants the field-by-field comparison
plus one tweak. It never consults the type’s own Equals, which is
the implementation being written, so it does not loop; each field still
compares through its own type’s equality.
Only a type that a Bjolang module declares is compared field by field. A
string, a number, a List or any other type compares with its own
equality, and an array element by element. The fields are found by
reflection, those of base types included, and cached per type: an escape
hatch, not a fast path.
See also: structural-hash, =, hash-combine
structural-hash
function ↑ Functions
(: structural-hash (-> %a int))
A hash over a value’s fields, without the type’s own Eq.
a- The value.
- returns
- A hash that agrees with structural-equals; 0 for null.
Folds the fields’ hashes in declaration order, and an array’s elements in
order. A type that is compared with its own equality has its own hash. It
agrees with
structural-equals about what is equal, and is not the hash C#
would have written bit for bit.
See also: structural-equals, hash-combine
hash-combine
function ↑ Functions
(: hash-combine (-> int int int))
Two hashes folded into one.
h1- The first hash.
h2- The second.
- returns
- A hash of the pair. Order matters.
(defun (eq-hash p) (hash-combine (eq-hash (record-ref p x))
(eq-hash (record-ref p y))))
What an eq-hash over several fields folds with.
System.HashCode.Combine, so (hash-combine a b) and
(hash-combine b a) differ, and the value differs from one run of
the program to the next.
See also: eq-hash, structural-hash
unhashable
function ↑ Functions
(: unhashable (-> string int))
The eq-hash of a type that has none: it throws, naming the type.
type-name- The type's name, for the message.
- returns
- Nothing: it always throws.
- raises
System.InvalidOperationException - Always, saying the type cannot be a Map or Set key.
(impl (Eq Counter)
(defun (= a b) (structural-equals a b))
(defun (eq-hash c) (unhashable "Counter")))
A record with a mutable field has no lawful hash: hashing the field
breaks the rule that a key’s hash does not change, and leaving it out
breaks the rule that equal values hash alike. type/derive writes
this for such a type, and it is how a hand-written implementation says
its type is not a key. It is loud rather than silent because the
alternative is a Map that loses an entry the next time the field
is written.
See also: hash-combine, eq-hash
eq-comparer
function ↑ Functions
(: eq-comparer (-> (System.Collections.Generic.IEqualityComparer %a)))
The .NET equality comparer that agrees with = at a type.
- returns
- An IEqualityComparer for the type the call is used at.
(defun (hashset-empty) (clr-hashset-empty (eq-comparer)))
Used when creating collections so that keys are compared using =
and hashed using eq-hash. If the type’s own .NET equality matches
Bjolang’s (which is almost always true), it returns .NET’s default comparer;
otherwise, it delegates directly to the type’s Eq implementation.
See also: ord-comparer, =, eq-hash
ord-comparer
function ↑ Functions
(: ord-comparer (-> (System.Collections.Generic.IComparer %a)))
The .NET comparer that agrees with compare at a type.
- returns
- An IComparer for the type the call is used at.
The ordering counterpart of eq-comparer: returns .NET’s default
comparer when the type’s CompareTo agrees with its Ord
implementation, and delegates to Ord otherwise.
See also: eq-comparer, compare
raise
function ↑ Functions
(: raise (-> System.Exception %a))
Throws an exception, keeping the stack trace it already has.
e- The exception.
- returns
- Nothing: it never returns, so it fits where any type is wanted.
(match (parse s)
((Ok n) n)
((Err e) (raise e)))
The counterpart of try, which turns the failures it names into
values: this is how one gets back out. An exception that was caught and
is raised again keeps the stack trace of where it first failed.
Its result type is free because it never returns, so it can stand in a
match arm whose siblings produce a value.
See also: Err, panic!
seq-empty
function ↑ Functions
(: seq-empty (-> (Seq %a)))
The empty sequence.
- returns
- A Seq with no elements.
See also: seq-empty?, seq-unfold
seq-empty?
function ↑ Functions
(: seq-empty? (-> (Seq %a) bool))
Whether a sequence has no elements.
s- The sequence.
- returns
- #t when it yields nothing.
Starts a walk of s and pulls at most one element, so over a
source with effects it runs them as far as that element.
See also: first, empty?
seq-head
function ↑ Functions
(: seq-head (-> (Seq %a) %a))
Deprecated: use first. The first element of a sequence.
s- The sequence. Not empty.
- returns
- The first element it yields.
- raises
System.InvalidOperationException - When s is empty.
first takes any iterable, and answers (Some x), or
None for an empty one. A use of seq-head warns, and it goes
in a later release. There is no seq-tail, since a Seq has
no rest to step to; (drop 1 s) is the sequence without its first
element.
See also: first
seq-map
function ↑ Functions
(: seq-map (-> (-> %a %b) (Seq %a) (Seq %b)))
Deprecated: use map. A sequence of a function applied to each element, lazily.
f- The function.
s- The sequence.
- returns
- A Seq of the transformed elements, evaluated as pulled.
map takes any iterable and does the same to a sequence. A use of
seq-map warns, and it goes in a later release.
See also: map
seq-filter
function ↑ Functions
(: seq-filter (-> (-> %a bool) (Seq %a) (Seq %a)))
Deprecated: use filter. A sequence of the elements that satisfy a predicate, lazily.
f- The predicate.
s- The sequence.
- returns
- A Seq of the elements where (f x) is true.
filter takes any iterable and does the same to a sequence. A use
of seq-filter warns, and it goes in a later release.
See also: filter
seq-take
function ↑ Functions
(: seq-take (-> (Seq %a) int (Seq %a)))
Deprecated: use take. A sequence of the first n elements, lazily.
s- The sequence.
n- How many. Zero or less gives the empty sequence.
- returns
- A Seq of s's first n elements, or all of them if it has fewer.
(take n s) takes any iterable and does the same to a sequence.
Its arguments are in the other order. A use of seq-take warns,
and it goes in a later release.
See also: take
seq-drop
function ↑ Functions
(: seq-drop (-> (Seq %a) int (Seq %a)))
Deprecated: use drop. A sequence without its first n elements, lazily.
s- The sequence.
n- How many to skip. Zero or less skips none.
- returns
- A Seq of what follows; empty when s has no more than n.
(drop n s) takes any iterable and does the same to a sequence.
Its arguments are in the other order. A use of seq-drop warns,
and it goes in a later release.
See also: drop
seq-unfold
function ↑ Functions
(: seq-unfold (-> (-> %s (Option (Tuple %a %s))) %s (Seq %a)))
A sequence generated from a state, lazily.
f- Maps a state to (Some (Tuple x next-state)), the next element and the state after it, or to None to end.
state- The first state.
- returns
- A Seq of the elements f produces, until it returns None.
(take 5 (seq-unfold (fun (n) (Some (Tuple n (* 2 n)))) 1))
; 1 2 4 8 16
seq-range
function ↑ Functions
(: seq-range (-> int int (Seq int)))
The ints from start up to but not including stop, as a sequence.
start- The first, included.
stop- The bound, not included. At or below start, the sequence is empty.
- returns
- A lazy Seq of ints.
See also: range, seq-unfold
seq-append
function ↑ Functions
(: seq-append (-> (Seq %a) (Seq %a) (Seq %a)))
One sequence followed by another, lazily.
s1- The first.
s2- The second, walked once s1 is exhausted.
- returns
- A Seq of s1's elements, then s2's.
See also: flat-map
seq-length
function ↑ Functions
(: seq-length (-> (Seq %a) int))
Deprecated: use count. How many elements a sequence yields.
s- The sequence.
- returns
- The count.
count takes any iterable, and fuses with a chain under it. A use
of seq-length warns, and it goes in a later release.
See also: count
seq->list
function ↑ Functions
(: seq->list (-> (Seq %a) (List %a)))
Deprecated: use ->list. A sequence’s elements as a list.
s- The sequence, walked to the end.
- returns
- A list of its elements, in order.
->list takes any iterable, and fuses with a chain under it. A use
of seq->list warns, and it goes in a later release.
See also: ->list
seq->vec
function ↑ Functions
(: seq->vec (-> (Seq %a) (Vec %a)))
Deprecated: use ->vec. A sequence’s elements as a vec.
s- The sequence, walked to the end.
- returns
- A vec of its elements, in order.
->vec takes any iterable, and fuses with a chain under it. A use
of seq->vec warns, and it goes in a later release.
See also: ->vec
seq-enumerator
function ↑ Functions
(: seq-enumerator (-> (Seq %a) (SeqEnumerator %a)))
Starts one walk of a sequence, with .NET’s enumerator protocol.
s- The sequence.
- returns
- A fresh enumerator of s, before its first element.
(def e (seq-enumerator s))
(let go ()
(when (seq-enumerator-next! e)
(println (seq-enumerator-current e))
(go)))
What Iterable’s implementation for Seq walks with. It holds
the sequence’s .NET enumerator, so each element is made once, and it has
.NET’s protocol: seq-enumerator-next! is MoveNext and
seq-enumerator-current is Current.
It is not a cursor. A cursor, such as vec-cursor, is a position
that does not change: vec-cursor-done? asks and moves nothing, and
vec-cursor-next answers a new cursor. Stepping an enumerator moves
it, for everyone who holds it. A for-each, a loop or a
:for does the stepping, so most programs never hold one.
See also: seq-enumerator-next!, seq-enumerator-current, seq-enumerator-end!
seq-enumerator-next!
function ↑ Functions
(: seq-enumerator-next! (-> (SeqEnumerator %a) bool))
Steps an enumerator to the next element, and answers whether there is one.
e- The enumerator.
- returns
- #t when e is on an element; #f when the sequence is exhausted.
.NET’s MoveNext: call it once before each
seq-enumerator-current, the first time too. When it returns
#f, the enumerator is disposed, which closes a file or stream that
the sequence opened for this walk. Calling it again goes on returning
#f.
See also: seq-enumerator, seq-enumerator-current
seq-enumerator-current
function ↑ Functions
(: seq-enumerator-current (-> (SeqEnumerator %a) %a))
The element an enumerator is on.
e- The enumerator, after seq-enumerator-next! returned #t.
- returns
- The element.
See also: seq-enumerator-next!
seq-enumerator-end!
function ↑ Functions
(: seq-enumerator-end! (-> (SeqEnumerator %a) void))
Ends a walk before the sequence is exhausted.
e- The enumerator.
Disposes the underlying enumerator, which closes a file or stream that the
sequence opened for this walk. A loop calls it, through
iterable-end, when it stops before the end. After the first call,
and after seq-enumerator-next! returned #f, it does nothing.
See also: seq-enumerator, seq-enumerator-next!
Cons
function ↑ Functions
(: Cons (-> %a (List %a) (List %a)))
A list with one more element in front.
x- The new first element.
xs- The list it goes in front of, which is shared, not copied.
- returns
- A list whose head is x and whose tail is xs.
(Cons 1 (Cons 2 Nil)) ; (1 2)
(match xs
(Nil 0)
((Cons h _) h))
One of the two cases of a list, with Nil. Also used in pattern
matching to deconstruct a non-empty list: (Cons h t).
cons is the same function under a lower-case name.
cons
function ↑ Functions
(: cons (-> %a (List %a) (List %a)))
A list with one more element in front.
x- The new first element.
xs- The list it goes in front of, which is shared, not copied.
- returns
- A list whose head is x and whose tail is xs.
(cons 0 (list 1 2)) ; (0 1 2)
The same as Cons. Only one cell is allocated: a list is
immutable, so the new list and xs share every cell of xs.
See also: Cons, list, list-empty
list
function ↑ Functions
(: list (-> (Array %a) (List %a)))
A list of the arguments, in the order they are given.
items ...- The elements. None makes the empty list.
- returns
- A new list of items.
(list 1 2 3) ; (1 2 3)
(list) ; ()
Taken as a value, as in (def f list), it is the function from an
Array of elements to a list.
list-empty
function ↑ Functions
(: list-empty (-> (List %a)))
The empty list.
- returns
- The same list as
Nil.
See also: Nil, list-empty?
list-head
function ↑ Functions
(: list-head (-> (List %a) %a))
The first element of a list.
xs- The non-empty list.
- returns
- Its first element.
- raises
System.InvalidOperationException - When xs is empty.
See also: list-tail, list-empty?, Cons
list-tail
function ↑ Functions
(: list-tail (-> (List %a) (List %a)))
A list without its first element.
xs- The non-empty list.
- returns
- The list following the first element (shares structural tail of xs).
- raises
System.InvalidOperationException - When xs is empty.
See also: list-head, over-list
list-empty?
function ↑ Functions
(: list-empty? (-> (List %a) bool))
Whether a list has no elements.
xs- The list.
- returns
- #t for
Nil, #f for any other list.
See also: Nil, list-length
list-length
function ↑ Functions
(: list-length (-> (List %a) int))
How many elements a list has.
xs- The list.
- returns
- The number of elements, 0 for the empty list.
O(n): a list stores no count, so this walks it. To ask only whether a
list is empty, list-empty? costs nothing.
See also: list-empty?, listbuilder-length
list-ref
function ↑ Functions
(: list-ref (-> (List %a) int %a))
The element at an index of a list.
xs- The list.
i- The index, from 0. Not negative, and less than the length.
- returns
- The element at i.
- raises
System.ArgumentOutOfRangeException - When i is negative, or not less than the length of xs.
O(i): it walks from the front. For many lookups by index, convert with
list->vec first.
See also: list-head, list->vec
list-reverse
function ↑ Functions
(: list-reverse (-> (List %a) (List %a)))
A list’s elements in the opposite order.
xs- The list to reverse.
- returns
- A new list, last element first.
See also: list-foldr
list->seq
function ↑ Functions
(: list->seq (-> (List %a) (Seq %a)))
A list seen as a sequence.
xs- The list.
- returns
- A seq of xs's elements, in order.
Nothing is copied: the seq is the list itself, and walking it walks the list. Since the list is immutable, it can be walked any number of times.
See also: list->vec, listbuilder-add-range!
reader->list
function ↑ Functions
(: reader->list (-> Bjolang.Runtime.BjoInputPort (List string)))
The lines a reader has left, as a list.
r- The reader. It is read to its end and not closed.
- returns
- Each line without its line ending, in order.
It blocks the thread until the reader is out of lines.
See also: list->vec
listbuilder-empty
function ↑ Functions
(: listbuilder-empty (-> (ListBuilder %a)))
A new builder, empty, for making a list from the front to the back.
- returns
- A builder with no elements.
(def b (listbuilder-empty))
(listbuilder-add! b 1)
(listbuilder-add! b 2)
(listbuilder->list b) ; (1 2)
Adding to a builder appends in O(1), which consing cannot do: the alternative is to cons onto the front and reverse at the end.
See also: listbuilder-add!, listbuilder->list, list->builder
list->builder
function ↑ Functions
(: list->builder (-> (List %a) (ListBuilder %a)))
A new builder holding a copy of a list’s elements.
xs- The list, which later changes to the builder do not touch.
- returns
- A builder with xs's elements, in order.
See also: list->listbuilder, listbuilder-empty
list->listbuilder
function ↑ Functions
(: list->listbuilder (-> (List %a) (ListBuilder %a)))
A new builder holding a copy of a list’s elements.
xs- The list, which later changes to the builder do not touch.
- returns
- A builder with xs's elements, in order.
The same as list->builder.
See also: list->builder
listbuilder-add!
function ↑ Functions
(: listbuilder-add! (-> (ListBuilder %a) %a void))
Adds an element to the end of a builder, in place.
b- The builder.
x- The element.
- raises
System.InvalidOperationException - When b has already been made into a list.
See also: listbuilder-add-range!, listbuilder->list
listbuilder-add-range!
function ↑ Functions
(: listbuilder-add-range! (-> (ListBuilder %a) (Seq %a) void))
Adds every element of a sequence to the end of a builder, in place.
b- The builder.
s- The elements, added in the order the seq yields them.
- raises
System.InvalidOperationException - When b has already been made into a list.
See also: listbuilder-add!, list->seq
listbuilder-length
function ↑ Functions
(: listbuilder-length (-> (ListBuilder %a) int))
How many elements a builder holds.
b- The builder.
- returns
- The number of elements added so far. The builder keeps a count, so this does not walk.
- raises
System.InvalidOperationException - When b has already been made into a list.
See also: list-length
listbuilder->list
function ↑ Functions
(: listbuilder->list (-> (ListBuilder %a) (List %a)))
The list a builder has built.
b- The builder. It cannot be used again afterwards.
- returns
- A list of the elements added, in order.
- raises
System.InvalidOperationException - When b has already been made into a list.
Nothing is copied: the cells the builder linked become the list. That is why the builder is finished after it, and every later operation on it, this one included, raises.
See also: listbuilder-empty
vec-empty
function ↑ Functions
(: vec-empty (-> (Vec %a)))
An empty vec.
- returns
- A vec with no elements.
The constructor. The predicate is vec-empty?.
See also: vec-empty?, vecbuilder-empty
vec-empty?
function ↑ Functions
(: vec-empty? (-> (Vec %a) bool))
Whether a vec has no elements.
v- The vec.
- returns
- #t when its length is 0.
O(1): a vec stores its count, and this reads it.
See also: vec-empty, vec-length
vec-length
function ↑ Functions
(: vec-length (-> (Vec %a) int))
How many elements a vec has.
v- The vec.
- returns
- Its number of elements.
O(1): a vec stores its count.
See also: vec-empty?
vec-ref
function ↑ Functions
(: vec-ref (-> (Vec %a) int %a))
The element of a vec at an index.
v- The vec.
i- Zero-based index (0 <= i < length).
- returns
- The element at i.
- raises
System.IndexOutOfRangeException - When i is negative or not less than the length.
A descent of the tree from the root, unless i is in the last few
elements, which are kept in an array of their own. To visit every
element, a (:for x v) loop, in-vec or vec-for-each
walks the leaf arrays instead and costs less per element.
See also: vec-set, vec-length
vec-set
function ↑ Functions
(: vec-set (-> (Vec %a) int %a (Vec %a)))
Returns a vec with the element at an index replaced.
v- The persistent vector (unmodified).
i- Zero-based index (0 <= i < length).
x- The new element.
- returns
- A new vec with x at i.
- raises
System.IndexOutOfRangeException - When i is negative or not less than the length.
See also: vec-ref, vecbuilder-set!
vec-pop
function ↑ Functions
(: vec-pop (-> (Vec %a) (Vec %a)))
A vec without its last element.
v- The vec, which is left as it was. Not empty.
- returns
- A new vec, one shorter.
- raises
System.InvalidOperationException - When v is empty.
See also: vec-try-pop, vec-pop-first, vec-remove-at, vec-slice
vec-pop-first
function ↑ Functions
(: vec-pop-first (-> (Vec %a) (Vec %a)))
A vec without its first element.
v- The vec, which is left as it was. Not empty.
- returns
- A new vec, one shorter.
- raises
System.InvalidOperationException - When v is empty.
(vec-slice v 1 (- (vec-length v) 1)).
See also: vec-try-pop-first, vec-pop, vec-slice
vec-append
function ↑ Functions
(: vec-append (-> (Vec %a) (Vec %a) (Array (Vec %a)) (Vec %a)))
Concatenates two or more vecs into a single vec.
a- The first part (unmodified).
b- The second part (unmodified).
more ...- More parts, in order (unmodified).
- returns
- A new vec with a's elements followed by b's, then those of each vec in more.
(vec-append [1 2] [3]) ; [1 2 3]
(vec-append [1] [2] [3 4]) ; [1 2 3 4]
(apply vec-append first second parts) ; with parts a list of vecs
Two vecs are joined by an RRB concatenation, which joins the two trees
rather than copying every element. When either vector is empty it
returns the other. The result may be relaxed; vec-compact
rebuilds it dense.
With more than two, a vec of 256 elements or more is joined in the same way, and a smaller one is copied into full leaves at the end of the result. That is cheaper than one merge for each: 50 000 vecs of 20 elements took 4 ms, against 16 ms by merging two at a time, and the result is dense.
See also: vec-add, vec-split, vec-compact
vec-compact
function ↑ Functions
(: vec-compact (-> (Vec %a) (Vec %a)))
Returns a vec with the same elements in a compact, dense tree.
v- The persistent vector (unmodified).
- returns
- A vec equal to v, rebuilt from the front.
O(n): every element is added to a new builder. Inserting and merging can leave relaxed nodes that make the tree deeper than it needs to be; this is for when that has made access slower. A vec small enough to have no tree is returned unchanged.
See also: vec-insert, vec-append
vec->seq
function ↑ Functions
(: vec->seq (-> (Vec %a) (Seq %a)))
The elements of a vec, as a lazy sequence.
v- The vec.
- returns
- A sequence of v's elements, in order.
Nothing is read until the sequence is walked, and it may be walked more than once, since the vec does not change. Each element is read by index.
See also: ->vec, vec->list
reader->vec
function ↑ Functions
(: reader->vec (-> Bjolang.Runtime.BjoInputPort (Vec string)))
Every remaining line of a .NET text reader, as a vec.
r- The reader. It is read to the end and not closed.
- returns
- The lines, without their line terminators.
Lines as TextReader.ReadLine splits them, each converted to a
Bjolang string and added to a builder. The drains in (std ports)
are the usual way to read a port into a vec.
See also: vecbuilder-empty
vecbuilder-empty
function ↑ Functions
(: vecbuilder-empty (-> (VecBuilder %a)))
A new, empty vec builder.
- returns
- A builder to add to in place and freeze with vecbuilder->vec.
(def b (vecbuilder-empty))
(vecbuilder-add! b 1)
(vecbuilder-add! b 2)
(vecbuilder->vec b) ; [1 2]
The way to make a vec of many elements without a new vec per element.
The vecing collector is one of these under a loop.
See also: vecbuilder-add!, vecbuilder->vec, vec->vecbuilder, Vecing
vecbuilder-empty/small
function ↑ Functions
(: vecbuilder-empty/small (-> (VecBuilder %a)))
A new, empty vec builder for a vec that is likely small.
- returns
- A builder to add to in place and freeze with vecbuilder->vec.
The same as vecbuilder-empty, except for how it allocates.
vecbuilder-empty gives the builder room for 32 elements at the
first add. This one gives it room for 4, and doubles the room up to 32
as elements are added. A vec of 4, 8, 16 or 32 elements then takes the
builder’s array with no copy.
See also: vecbuilder-empty, VecingSmall
vec->vecbuilder
function ↑ Functions
(: vec->vecbuilder (-> (Vec %a) (VecBuilder %a)))
A builder holding a vec’s elements, to go on adding to.
v- The vec. Changing the builder does not change it.
- returns
- A builder starting with v's elements.
The builder shares v’s tree and copies a part before it writes to it.
See also: vecbuilder-empty, vecbuilder->vec
vecbuilder-add!
function ↑ Functions
(: vecbuilder-add! (-> (VecBuilder %a) %a void))
Adds an element to the end of a vec builder, in place.
b- The builder.
x- The element to add.
See also: vecbuilder-set!, vec-add, vecbuilder->vec
vecbuilder-set!
function ↑ Functions
(: vecbuilder-set! (-> (VecBuilder %a) int %a void))
Replaces the element at an index in a vec builder, in place.
b- The builder.
i- From 0. Less than the builder's length.
x- The new element.
- raises
System.IndexOutOfRangeException - When i is negative or not less than the length.
See also: vecbuilder-ref, vec-set
vecbuilder-ref
function ↑ Functions
(: vecbuilder-ref (-> (VecBuilder %a) int %a))
The element at an index in a vec builder.
b- The builder.
i- From 0. Less than the builder's length.
- returns
- The element at i.
An index out of range raises System.IndexOutOfRangeException, as
vec-ref does.
See also: vecbuilder-set!, vecbuilder-length, vec-ref
vecbuilder-length
function ↑ Functions
(: vecbuilder-length (-> (VecBuilder %a) int))
How many elements a vec builder holds.
b- The builder.
- returns
- Its number of elements.
See also: vecbuilder-ref
vecbuilder->vec
function ↑ Functions
(: vecbuilder->vec (-> (VecBuilder %a) (Vec %a)))
The vec a builder holds.
b- The builder. It may be added to afterwards.
- returns
- A vec of the builder's elements.
The builder stays usable: what is added or set in it afterwards does not change the previously returned vec.
See also: vecbuilder-empty, vec->vecbuilder
vec-cursor
function ↑ Functions
(: vec-cursor (-> (Vec %a) (VecCursor %a)))
A cursor on the first element of a vec, for walking it front to back.
v- The vec.
- returns
- A cursor on the first element, or a finished cursor for an empty vec.
What Vec’s Iterable implementation walks with. The cursor
is a value that walks the vec’s leaf arrays: an array read per element,
a lookup per leaf of 32 elements, and nothing allocated. A vec of up to
32 elements is one array.
vec-cursor-done? and vec-cursor-current only read a
cursor, and vec-cursor-next answers the cursor one element on.
See also: vec-cursor-done?, vec-cursor-current, vec-cursor-next, vec-cursor-slice
vec-cursor-slice
function ↑ Functions
(: vec-cursor-slice (-> (Vec %a) int int (VecCursor %a)))
A cursor for walking a run of a vec’s elements front to back.
v- The vec.
from- The first index walked, from 0.
count- How many elements. from plus count is at most the length.
- returns
- A cursor on the first element of the run, or a finished cursor for an empty run.
- raises
System.ArgumentOutOfRangeException - When the run is not in v.
What VecSlice’s Iterable implementation walks with, and so
what in-vec walks with. The cursor is the one vec-cursor
makes, so it is read and moved on with the same functions.
See also: vec-cursor, in-vec
vec-cursor-done?
function ↑ Functions
(: vec-cursor-done? (-> (VecCursor %a) bool))
Whether a vec cursor has walked past the last element.
c- The cursor.
- returns
- #t when the walk is over; #f when the cursor is on an element.
See also: vec-cursor, vec-cursor-current, vec-cursor-next
vec-cursor-current
function ↑ Functions
(: vec-cursor-current (-> (VecCursor %a) %a))
The element a vec cursor is on.
c- The cursor, when vec-cursor-done? says #f.
- returns
- The element.
See also: vec-cursor, vec-cursor-done?, vec-cursor-next
vec-cursor-next
function ↑ Functions
(: vec-cursor-next (-> (VecCursor %a) (VecCursor %a)))
The cursor one element further on.
c- The cursor, when vec-cursor-done? says #f.
- returns
- A cursor on the next element, or a finished cursor after the last.
The cursor given does not change, so it still reads the element it was on.
See also: vec-cursor, vec-cursor-done?, vec-cursor-current
make-array
function ↑ Functions
(: make-array (-> int %a (Array %a)))
A new .NET array of a length.
n- The length.
- returns
- An array of n elements, each .NET's default for the type: zero for a number.
See also: array-ref, array-set!, array-resize
array-ref
function ↑ Functions
(: array-ref (-> (Array %a) int %a))
The element of an array at an index.
a- The array.
i- From 0. Less than the length.
- returns
- The element at i.
a[i], with .NET’s bounds check.
See also: array-set!, array-length, vec-ref
array-set!
function ↑ Functions
(: array-set! (-> (Array %a) int %a void))
Replaces the element of an array at an index, in place.
a- The array, which is changed.
i- From 0. Less than the length.
x- The new element.
a[i] = x, with .NET’s bounds check.
See also: array-ref
array-length
function ↑ Functions
(: array-length (-> (Array %a) int))
How many elements an array has.
a- The array.
- returns
- Its length.
See also: make-array
array-resize
function ↑ Functions
(: array-resize (-> (Array %a) int (Array %a)))
A new array of another length, holding as much of an array as fits.
a- The array, which is left as it was.
n- The new length. Larger grows, smaller shrinks.
- returns
- A new array of n elements: a's first ones, then .NET's default for the type.
What a growable array is written over: make-array, and this when
it fills up. It always copies, so the old array is not the new one.
See also: make-array, array-copy!
array->vec
function ↑ Functions
(: array->vec (-> (Array %a) (Vec %a)))
A vec of an array’s elements.
a- The array, which is copied: changing it afterwards does not change the vec.
- returns
- A vec of a's elements, in order.
The elements go straight into the tree’s leaves in one walk, with no add per element, so an array is the cheapest thing to build a vec out of. It suits making a great many small vecs, where a builder is sized for large ones.
See also: subarray->vec, vecbuilder-empty
subarray->vec
function ↑ Functions
(: subarray->vec (-> (Array %a) int int (Vec %a)))
A vec of a run of an array’s elements.
a- The array, which is copied.
start- The first index taken, from 0.
count- How many elements. start plus count is at most the length.
- returns
- A vec of count elements, a's from start on.
Start and count, as vec-slice takes them.
See also: array->vec, vec-slice
string-count
function ↑ Functions
(: string-count (-> string int))
The number of characters in a string.
s- The string.
- returns
- How many characters (Unicode scalar values) s holds.
O(n): the characters are counted, not stored. string-length is
the O(1) byte length. length on a string returns this count as well.
See also: string-length, length
string-empty?
function ↑ Functions
(: string-empty? (-> string bool))
Whether a string has no characters.
s- The string.
- returns
- #t for the empty string.
See also: string-length
string->clr-string
function ↑ Functions
(: string->clr-string (-> string System.String))
The same text as a .NET System.String.
s- The string.
- returns
- A UTF-16 System.String with the same characters.
A .NET member that takes a System.String directly is converted at
the call, so this is needed only for a .NET string inside another type,
such as an element of a (Seq System.String) or the argument of a
Func.
See also: clr-string->string
string-search
function ↑ Functions
(: string-search (-> string string (Option StringCursor)))
Where the first occurrence of a text in a string starts.
s- The string to search.
needle- The text to look for.
- returns
- (Some cursor) on the start of the first occurrence, or None. An empty needle is found at the start.
(match (string-search line "=")
((Some c) (substring line (string-cursor-start line) c)) ; the key
(None line))
Ordinal. The returned cursor can be passed directly to
substring; there is no byte index to get wrong. In a slice, the
cursor is a position in the string the slice was taken from.
See also: string-search-backward, string-find, substring, string-contains?
string-search-backward
function ↑ Functions
(: string-search-backward (-> string string (Option StringCursor)))
Where the last occurrence of a text in a string starts.
s- The string to search.
needle- The text to look for.
- returns
- (Some cursor) on the start of the last occurrence, or None. An empty needle is found at the end.
See also: string-search, substring
string-search-any
function ↑ Functions
(: string-search-any (-> string string StringCursor (Option StringCursor)))
Where the first character of a set is, at or after a cursor.
s- The string to search.
chars- The set, as a string of its characters. Their order does not matter.
start- Where to start, a cursor of s.
- returns
- (Some cursor) on the first character at or after start that is in chars, or None. An empty set is never found.
;; `&` and `<` as HTML has them. The text between them is copied whole.
(def b (stringbuilder-empty))
(let go ((from (string-cursor-start s)))
(match (string-search-any s "&<" from)
(None (stringbuilder-add-substring! b s from (string-cursor-end s)))
((Some at)
(stringbuilder-add-substring! b s from at)
(stringbuilder-add-string! b (if (char=? (string-cursor-ref s at) #\&) "&" "<"))
(go (string-cursor-next s at)))))
When every character of the set is ASCII, the search is a vectorized
search of the bytes, which is many times faster than a
string-find that tests each character. An ASCII byte is never part
of a longer character in UTF-8, so the cursor found is on a character. A
set with a character outside ASCII is searched one character at a time.
The set a string makes is kept for as long as the string is, so a set
written once, as a literal or a def, is made once. A set that is a
slice of a longer string is made at each call.
In a slice, the cursor is a position in the string the slice was taken
from, as for string-search.
See also: string-search, string-find, stringbuilder-add-substring!
substring
function ↑ Functions
(: substring (-> string StringCursor StringCursor string))
The text between two cursors.
s- The string.
start- Where the text begins.
end- Where it ends, not included. Not before start.
- returns
- The characters from start up to end, with bytes of their own; s itself when that is all of it.
- raises
System.ArgumentException - When start is after end, or a cursor is not on a character boundary of s.
- raises
System.ArgumentOutOfRangeException - When a cursor is outside s.
(substring s (string-cursor-next s (string-cursor-start s))
(string-cursor-end s)) ; all but the first character
See also: substring/slice, string-search, string-find, string-cursor-start
substring/slice
function ↑ Functions
(: substring/slice (-> string StringCursor StringCursor string))
The text between two cursors, as a slice of the string.
s- The string.
start- Where the text begins.
end- Where it ends, not included. Not before start.
- returns
- The characters from start up to end, sharing s's bytes.
- raises
System.ArgumentException - When start is after end, or a cursor is not on a character boundary of s.
- raises
System.ArgumentOutOfRangeException - When a cursor is outside s.
A slice is a string like any other: it equals, hashes and orders by its text, and goes anywhere a string goes. Two things set it apart.
Its cursors are its source’s. A cursor found in a slice, by
string-search, string-find or a regex, is a position in
the string it was taken from, and (string-cursor-start sl) is
where the slice begins in it.
It keeps all of its source alive. A ten-byte slice of a megabyte keeps the megabyte. That is why the plain forms copy: a slice is for a scanner that cuts many short pieces out of one text and lets them go, not for keeping a piece.
See also: substring, string-copy
string-cursor-start
function ↑ Functions
(: string-cursor-start (-> string StringCursor))
A cursor on the first character of a string.
s- The string.
- returns
- The cursor where s begins. For the empty string it is also the end.
(let loop ((c (string-cursor-start s)))
(unless (string-cursor-end? s c)
(println (char->string (string-cursor-ref s c)))
(loop (string-cursor-next s c))))
A cursor is a position in a string, and what takes the place of an
index: there is no string-ref, since reaching the n-th character
of UTF-8 is O(n). A cursor costs what an int does, and stepping
it is O(1).
It is opaque. There is no conversion between cursors and numbers: a
cursor is made by string-cursor-start, string-cursor-end,
a search, or a step, so it always rests on a character boundary.
It does not carry its string, so every operation takes the string as well. A cursor of a slice is a cursor of the string the slice was taken from, and is where the slice begins in it. A cursor used with another string is caught only when it falls outside that string or inside one of its characters.
(:for ch s) walks a string faster than a cursor loop does; a
cursor is for when the positions are wanted.
See also: string-cursor-end, string-cursor-next, string-cursor-ref
string-cursor-end
function ↑ Functions
(: string-cursor-end (-> string StringCursor))
The past-the-end cursor of a string.
s- The string.
- returns
- The cursor after the last character: the bound a traversal stops at.
See also: string-cursor-end?, string-cursor-start, string-cursor-prev
string-cursor-end?
function ↑ Functions
(: string-cursor-end? (-> string StringCursor bool))
Whether a cursor has reached the end of its string.
s- The string.
c- A cursor of s.
- returns
- #t when c is the past-the-end cursor, and there is no character at it.
See also: string-cursor-end, string-cursor-ref
string-cursor-ref
function ↑ Functions
(: string-cursor-ref (-> string StringCursor char))
The character at a cursor.
s- The string.
c- A cursor of s, not at the end.
- returns
- The character c is on.
- raises
System.ArgumentOutOfRangeException - When c is at the end of s, or outside it.
- raises
System.ArgumentException - When c is not on a character boundary of s, as a cursor from another string may be.
Guard it with string-cursor-end?.
See also: string-cursor-ref+next, string-cursor-end?
string-cursor-next
function ↑ Functions
(: string-cursor-next (-> string StringCursor StringCursor))
The cursor on the next character.
s- The string.
c- A cursor of s, not at the end.
- returns
- The cursor after the character at c, which is the end after the last one.
- raises
System.ArgumentOutOfRangeException - When c is at the end of s, or outside it.
- raises
System.ArgumentException - When c is not on a character boundary of s.
Steps over all the bytes the character takes, so it lands on the next character whatever its width.
See also: string-cursor-prev, string-cursor-ref+next
string-cursor-prev
function ↑ Functions
(: string-cursor-prev (-> string StringCursor StringCursor))
The cursor on the previous character.
s- The string.
c- A cursor of s, not at the start.
- returns
- The cursor on the character before c.
- raises
System.ArgumentOutOfRangeException - When c is at the start of s, or outside it.
O(1): it steps back over at most three continuation bytes, and decodes nothing.
See also: string-cursor-next, string-cursor-end, string-fold-right
string-cursor-ref+next
function ↑ Functions
(: string-cursor-ref+next (-> string StringCursor (Tuple char StringCursor)))
The character at a cursor and the cursor after it, in one call.
s- The string.
c- A cursor of s, not at the end.
- returns
- A tuple of the character at c and the cursor on the next one.
- raises
System.ArgumentOutOfRangeException - When c is at the end of s, or outside it.
- raises
System.ArgumentException - When c is not on a character boundary of s.
(def (Tuple ch next) (string-cursor-ref+next s c))
Reading the byte at c provides both the character and the next
cursor in a single operation, whereas string-cursor-ref and
string-cursor-next each read and validate independently. The tuple
is a ValueTuple and does not allocate.
See also: string-cursor-ref, string-cursor-next
char->int
function ↑ Functions
(: char->int (-> char int))
The codepoint of a character.
c- The character.
- returns
- Its Unicode scalar value, from 0 to #x10FFFF, never a surrogate.
(char->int #\a) ; 97
A codepoint rather than a UTF-16 code unit: a character outside the
Basic Multilingual Plane returns its full scalar value, not a
surrogate. char->int is the same function under R6RS’s name.
See also: int->char, char->string
int->char
function ↑ Functions
(: int->char (-> int char))
The character with a given codepoint.
n- A Unicode scalar value: from 0 to #x10FFFF, outside the surrogates #xD800 to #xDFFF.
- returns
- The character.
- raises
System.ArgumentOutOfRangeException - When n is not a Unicode scalar value: negative, a surrogate, or above #x10FFFF.
(int->char 955) ; #\λ
See also: char->int
char->string
function ↑ Functions
(: char->string (-> char string))
A string of one character.
c- The character.
- returns
- The one-character string.
For a character outside ASCII the string is longer than one in
string-length, which counts UTF-8 bytes: an astral character
gives a string of string-length 4 and string-count 1.
This is the way from a char to a .NET method that wants text: a
Bjolang char is a codepoint, not a C# char.
See also: char->int, string-length, string-count
keyword?
function ↑ Functions
(: keyword? (-> %a bool))
Whether a value is a keyword.
x- Any value.
- returns
- #t when x is a Keyword at run time.
See also: symbol?, string->keyword
keyword->string
function ↑ Functions
(: keyword->string (-> Keyword string))
The name of a keyword.
k- The keyword.
- returns
- Its name, without the colon: "foo" for :foo.
See also: string->keyword, symbol->string
string->keyword
function ↑ Functions
(: string->keyword (-> string Keyword))
The keyword with a given name.
s- The name, without the colon.
- returns
- The interned keyword corresponding to s.
Keywords are interned, so (= a b) on two of them is a reference
comparison.
See also: keyword->string, string->symbol
symbol?
function ↑ Functions
(: symbol? (-> %a bool))
Whether a value is a symbol.
x- Any value.
- returns
- #t when x is a Symbol at run time.
See also: keyword?, string->symbol
symbol->string
function ↑ Functions
(: symbol->string (-> Symbol string))
The name of a symbol.
sym- The symbol.
- returns
- Its name: "foo" for 'foo.
See also: string->symbol, keyword->string
string->symbol
function ↑ Functions
(: string->symbol (-> string Symbol))
The symbol with a given name.
s- The name.
- returns
- The interned symbol corresponding to s.
Symbols are interned, so (= a b) on two of them is a reference
comparison, and either can be a map key.
See also: symbol->string, string->keyword
stringbuilder-empty
function ↑ Functions
(: stringbuilder-empty (-> StringBuilder))
A new, empty string builder.
- returns
- A builder holding no text.
(def b (stringbuilder-empty))
(stringbuilder-add-string! b "ab")
(stringbuilder-add! b #\c)
(stringbuilder->string b) ; "abc"
A growable UTF-8 buffer, and the accumulator behind the stringing
collector. The append operations mutate the builder in place:
the builder remains the same object throughout.
Use one, or a (:acc out (stringing c)) clause, rather than
string-append in a loop, which copies the whole string at every
step. A builder also carries no colour, where writing to a string port
gives the writing function a suspending copy.
See also: stringbuilder-add!, stringbuilder-add-string!, stringbuilder->string
stringbuilder-add!
function ↑ Functions
(: stringbuilder-add! (-> StringBuilder char void))
Adds a character to the end of a string builder, in place.
b- The builder.
c- The character, encoded as UTF-8.
See also: stringbuilder-add-string!, stringbuilder-add-byte!
stringbuilder-add-string!
function ↑ Functions
(: stringbuilder-add-string! (-> StringBuilder string void))
Adds a string to the end of a string builder, in place.
b- The builder.
s- The string.
See also: stringbuilder-add!, stringbuilder-add-substring!
stringbuilder-add-substring!
function ↑ Functions
(: stringbuilder-add-substring! (-> StringBuilder string StringCursor StringCursor void))
Adds the text between two cursors of a string, in place.
b- The builder.
s- The string.
start- The first cursor, of s.
end- The cursor after the text, of s, not before start.
What (stringbuilder-add-string! b (substring s start end)) adds,
without the string substring makes. The bytes are copied as they
are, in one piece, and are not decoded. Cursors that are not of s, or are
in the wrong order, raise.
See also: stringbuilder-add-string!, string-search-any, substring
stringbuilder-add-bytes!
function ↑ Functions
(: stringbuilder-add-bytes! (-> StringBuilder (Array byte) int int void))
Adds a range of bytes of an array, as UTF-8, in place.
b- The builder.
bytes- The array.
start- The first byte, from 0.
end- The byte after the last, not before start and at most the array's length.
What stringbuilder-add-byte! adds a byte at a time, in one piece:
for a reader that copies a run of its input. The bytes are checked as
those are, when the text leaves the builder. A range outside the array
raises here.
See also: stringbuilder-add-byte!, stringbuilder->string
stringbuilder-add-long!
function ↑ Functions
(: stringbuilder-add-long! (-> StringBuilder long void))
Adds a long, written as long->string writes it, in place.
b- The builder.
n- The number.
The digits are written into the builder, without the string
long->string makes. An int is given as a long with
(cast long n).
See also: stringbuilder-add-double!, long->string
stringbuilder-add-double!
function ↑ Functions
(: stringbuilder-add-double! (-> StringBuilder double void))
Adds a double, written as double->string writes it, in place.
b- The builder.
d- The number.
The shortest text that reads back as the same double, written into the
builder without the string double->string makes. The same in every
culture.
See also: stringbuilder-add-long!, double->string
stringbuilder-add-byte!
function ↑ Functions
(: stringbuilder-add-byte! (-> StringBuilder int void))
Adds one UTF-8 byte to the end of a string builder, in place.
b- The builder.
n- The byte, from 0 to 255.
For a scanner that copies its input a byte at a time and already holds the number: it skips decoding and re-encoding a character.
A number outside 0 to 255 raises
System.ArgumentOutOfRangeException.
Validity. A builder never gives out invalid UTF-8. A character
of several bytes is incomplete until its last byte is added, so the
bytes are checked when the text leaves the builder, not here:
stringbuilder->string raises
System.InvalidOperationException if they do not form whole
characters, and so does a write of the builder to a port.
See also: stringbuilder-byte-ref, stringbuilder-add!, stringbuilder->string
stringbuilder-add-unit!
function ↑ Functions
(: stringbuilder-add-unit! (-> StringBuilder int void))
Adds one UTF-16 code unit to the end of a string builder, in place.
b- The builder.
n- The code unit, from 0 to 65535.
For a reader taking units from a .NET text port. A surrogate pair given
in two calls, high then low, becomes its one character. A surrogate
left unpaired makes stringbuilder->string raise. A number outside
0 to 65535 raises System.ArgumentOutOfRangeException.
See also: stringbuilder-add!, stringbuilder->string
stringbuilder-length
function ↑ Functions
(: stringbuilder-length (-> StringBuilder int))
How much text a string builder holds, in bytes.
b- The builder.
- returns
- The number of UTF-8 bytes added so far, not characters.
See also: stringbuilder-byte-ref, string-length
stringbuilder-byte-ref
function ↑ Functions
(: stringbuilder-byte-ref (-> StringBuilder int int))
One byte of what a string builder holds.
b- The builder.
i- The byte index, from 0, less than stringbuilder-length.
- returns
- The byte at i, from 0 to 255.
- raises
System.ArgumentOutOfRangeException - When i is negative or not less than the builder's length.
The counterpart of stringbuilder-add-byte!, for a scanner that
looks back at what it wrote. Indices are bytes, not characters.
See also: stringbuilder-add-byte!, stringbuilder-length
stringbuilder-clear!
function ↑ Functions
(: stringbuilder-clear! (-> StringBuilder void))
Empties a string builder for reuse, in place.
b- The builder.
The builder keeps the buffer it has grown, so a reader that builds many short strings does not pay for a new builder each time. Strings already made from it are unaffected.
See also: stringbuilder-empty
stringbuilder=?
function ↑ Functions
(: stringbuilder=? (-> StringBuilder string bool))
Whether a string builder holds exactly a given text.
b- The builder.
s- The text to compare with.
- returns
- #t when b's bytes are s's bytes.
Compares without building a string, which lets a reader ask whether the name it just buffered is one it has already interned without paying for the allocation.
See also: stringbuilder->string
stringbuilder->string
function ↑ Functions
(: stringbuilder->string (-> StringBuilder string))
The text a string builder holds, as a string.
b- The builder.
- returns
- A copy of the text so far.
- raises
System.InvalidOperationException - When bytes from stringbuilder-add-byte! or stringbuilder-add-bytes!, or a surrogate from stringbuilder-add-unit! left unpaired, do not form valid UTF-8.
The string is a copy: the builder keeps its text and can go on growing, and what is added afterwards does not change the string.
See also: stringbuilder-empty, stringbuilder-clear!
file-read-text
function ↑ Functions
(: file-read-text (-> %p string))
(file-read-text path)
The whole of a file, as one string.
path- The file to read.
- returns
- Everything the file holds.
For a file that fits in memory; a port reads one that does not. Opening
goes through the FS effect’s open-read-stream, and an
Err from it is raised, as the .NET methods raise: wrap the call in
try for a Result. The file is closed before this returns.
A bjoroutine calling it awaits the file rather than parking its thread.
See also: file-read-lines, file-read-bytes, file-write-text, open-input-file
file-write-text
function ↑ Functions
(: file-write-text (-> %p string void))
(file-write-text path contents)
Writes a string to a file, replacing what it held.
path- The file to write. Created if it is missing, emptied if it is there.
contents- The text to write.
Opened with Truncate through the FS effect; an error opening
it is raised. The text is flushed before the file is closed, and a
bjoroutine awaits the write.
See also: file-append-text, file-write-lines, file-read-text
file-append-text
function ↑ Functions
(: file-append-text (-> %p string void))
(file-append-text path contents)
Writes a string after what a file holds.
path- The file to add to. Created if it is missing.
contents- The text to add.
Opened with Append through the FS effect; an error opening
it is raised.
See also: file-write-text, file-append-bytes
file-read-lines
function ↑ Functions
(: file-read-lines (-> %p (#:mode LineMode) (Vec string)))
(file-read-lines path #:mode Any)
The lines of a file, without their line ends.
path- The file to read.
#:mode- What ends a line, as for read-line: Any by default.
- returns
- One string per line, in order.
By default "\n", "\r\n" and a lone "\r" each end
a line, as read-line reads them, a last line needs none,
and a final line end makes no empty line after it. The whole file is
read before this returns; file-read-lines/seq pulls the lines
lazily instead. An error opening the file is raised.
See also: file-write-lines, file-read-lines/seq, file-read-text, LineMode
file-write-lines
function ↑ Functions
(: file-write-lines (-> %p (Vec string) void))
(file-write-lines path lines)
Writes lines to a file, each followed by a newline, replacing what it held.
path- The file to write. Created if it is missing, emptied if it is there.
lines- The lines, without line ends.
Every line is followed by "\n", the last one too, on every OS, so
the same lines make the same bytes wherever they are written.
file-read-lines gives them back as long as no line holds a line
end of its own.
See also: file-read-lines, file-write-text
file-read-bytes
function ↑ Functions
(: file-read-bytes (-> %p (Array byte)))
(file-read-bytes path)
The whole of a file, as bytes.
path- The file to read.
- returns
- A new array holding everything the file holds.
Opened through the FS effect’s open-read-stream; an
Err from it is raised.
See also: file-write-bytes, file-read-text
file-write-bytes
function ↑ Functions
(: file-write-bytes (-> %p (Array byte) void))
(file-write-bytes path bytes)
Writes bytes to a file, replacing what it held.
path- The file to write. Created if it is missing, emptied if it is there.
bytes- What to write.
See also: file-append-bytes, file-read-bytes
file-append-bytes
function ↑ Functions
(: file-append-bytes (-> %p (Array byte) void))
(file-append-bytes path bytes)
Writes bytes after what a file holds.
path- The file to add to. Created if it is missing.
bytes- What to add.
See also: file-write-bytes, file-append-text
file-copy
function ↑ Functions
(: file-copy (-> %p %q (#:mode WriteMode) void))
(file-copy from to #:mode CreateNew)
Copies a file.
from- The file to copy.
to- Where the copy goes.
#:mode- How to is written: CreateNew, the default, Truncate or Append.
- raises
System.IO.IOException - When from and to are the same path.
(file-copy "a.txt" "b.txt") ; fails if b.txt exists
(file-copy "a.txt" "b.txt" #:mode Truncate) ; replaces it
CreateNew, the default, fails if to exists, so a copy never
loses a file by accident; it is the one function whose WriteMode
does not default to Truncate. Truncate replaces to,
and Append adds to it. The source is opened first, so a missing
one leaves to as it was. A copy onto its own path, compared after
path-absolute, is refused.
to may be the source under another name, a link say, and the text
of the paths cannot tell. So nothing that could empty the source is ever
opened: Truncate copies into a new file beside to and moves
it over to with MoveReplace, which replaces a link there
rather than writing through it, and Append copies the length the
source had when it was opened, so a file appended to itself grows once and
stops. The copy is a new file, with a modified time of its own.
See also: file-move, file-read-bytes
file-info
function ↑ Functions
(: file-info (-> %p (Option FsInfo)))
(file-info path)
What a path names: its kind, size, last write and whether it is a link.
path- The path to ask about.
- returns
- None when the path names nothing.
(match (file-info "notes.txt")
((Some info) (record-ref info size))
(None 0L))
Dispatched through the FS effect’s fs-info operation. A
symbolic link’s size and time are those of what it leads to, which is
what reading it reads; link? says it is one. With
(std datetime),
(unix-milliseconds->instant (record-ref info modified-ms)) converts
the timestamp to an (Option Instant).
A path that is no path at all, "" say, is None rather than
an error.
See also: FsInfo, file-exists?, directory-exists?, fs-info
file-exists?
function ↑ Functions
(: file-exists? (-> %p bool))
(file-exists? path)
Whether a path names a file.
path- The path to ask about.
- returns
- #t for a file, #f for a directory or for nothing.
See also: directory-exists?, file-info
file-delete
function ↑ Functions
(: file-delete (-> %p void))
(file-delete path)
Deletes a file.
path- The file to delete.
A missing file is not an error. Through the FS effect’s
fs-delete-file; an Err from it is raised.
See also: directory-delete, fs-delete-file
file-move
function ↑ Functions
(: file-move (-> %p %q (#:mode MoveMode) void))
(file-move from to #:mode MoveNew)
Moves or renames a file or a directory.
from- What to move.
to- Its new path.
#:mode- MoveNew, the default, or MoveReplace.
(file-write-text "config.tmp" text)
(file-move "config.tmp" "config" #:mode MoveReplace) ; never seen half-written
MoveNew fails if to exists. MoveReplace replaces a
file at to, in the one rename that moves the new one there, so
nothing ever sees to missing: write a temporary file, then move it
over the old one. A directory is never replaced, and never replaces
anything.
Through the FS effect’s fs-move; an Err from it is
raised.
file-read/seq
function ↑ Functions
(: file-read/seq (-> (-> InputPort %a) %p (Seq %a)))
(file-read/seq reader path)
The items a reader reads from a file, pulled lazily.
reader- Reads one item from the port. Called while the port is not at its end.
path- The file to read.
- returns
- A sequence of the items, which may be walked more than once.
The file is opened when the sequence is walked, not when it is made, so
every walk opens it afresh and reads from the start, using whatever
FS handler is active when iterated. It is closed when the walk ends:
at the end of the file; when a loop, find or any?
walking it stops early, or the consumer of a lazy seql over it
does (see iterable-end); and when an exception or a non-local
exit leaves the loop (see iterable-cleanup). A walk that is never ended, such
as an enumerator that .NET code takes and drops, leaves the file open
until the enclosing scope ends: the port is registered with the scope
that is ambient at the first pull. In main that is the end of the
program, so put such a walk in a with-scope to close it sooner.
A missing file raises on the first pull. (std ports)’
file->seq, which is built on this, reports it as a Result
at the call instead.
A seq body cannot await, so a bjoroutine pulling from this parks
its thread on every pull. In a bjoroutine, read the whole file with
file-read-lines, or stream it with port->stream.
See also: file-read-lines/seq, file-read-lines
file-read-lines/seq
function ↑ Functions
(: file-read-lines/seq (-> %p (#:mode LineMode) (Seq string)))
(file-read-lines/seq path #:mode Any)
The lines of a file, pulled lazily.
path- The file to read.
#:mode- What ends a line, as for read-line: Any by default.
- returns
- A sequence of the lines, without their line ends.
file-read/seq with read-line: opened at each walk, closed
when the walk ends, and never suspending.
See also: file-read/seq, file-read-lines, LineMode
path-absolute
function ↑ Functions
(: path-absolute (-> %p string))
(path-absolute path)
A path made absolute, against the current directory.
path- The path, relative or absolute.
- returns
- The full path, as a string. A path that is not UTF-8 raises an ArgumentException.
.NET’s Path.GetFullPath. Like the other path functions it works on
the text and asks nothing of the file system.
See also: current-directory, path-combine
path-combine
function ↑ Functions
(: path-combine (-> #:rest string string))
(path-combine #:rest parts)
Paths joined with the separator.
parts ...- The pieces, in order.
- returns
- The joined path.
(path-combine "src" "std" "prelude.bjo") ; "src/std/prelude.bjo" on Linux
.NET’s Path.Combine, so a piece that is itself an absolute path
starts the result over from it.
See also: path-directory, path-filename, path-absolute
path-filename
function ↑ Functions
(: path-filename (-> string (Option string)))
(path-filename path)
The last part of a path: the file’s name and extension.
path- The path.
- returns
- None for a path that ends in a separator, which names a directory.
(path-filename "src/main.bjo") ; (Some "main.bjo")
(path-filename "src/") ; None
See also: path-file-extension, path-directory
path-file-extension
function ↑ Functions
(: path-file-extension (-> string (Option string)))
(path-file-extension path)
The extension of a path’s file name, with its dot.
path- The path.
- returns
- None when the name has no extension.
(path-file-extension "main.bjo") ; (Some ".bjo")
(path-file-extension "Makefile") ; None
A name that is nothing but a dotted suffix, .bashrc, counts as an
extension, as it does to .NET.
See also: path-filename
path-directory
function ↑ Functions
(: path-directory (-> string (Option string)))
The directory part of a path: all of it but the last part.
path- The path.
- returns
- None for a root and for a bare file name.
(path-directory "src/main.bjo") ; (Some "src")
(path-directory "main.bjo") ; None
.NET’s Path.GetDirectoryName, mapping null and empty strings
to None. A builtin rather than a function of the prelude’s own,
for that reason.
See also: path-filename, path-combine
directory-exists?
function ↑ Functions
(: directory-exists? (-> %p bool))
(directory-exists? path)
Whether a path names a directory.
path- The path to ask about.
- returns
- #t for a directory, #f for a file or for nothing.
See also: file-exists?, file-info
directory-create
function ↑ Functions
(: directory-create (-> %p void))
(directory-create path)
Creates a directory, and every missing one along its path.
path- The directory to create.
One that is already there is not an error, so the call needs no guard.
Through the FS effect’s fs-create-directory; an Err
from it is raised.
See also: directory-delete, fs-create-directory
directory-delete
function ↑ Functions
(: directory-delete (-> %p void))
(directory-delete path)
Deletes an empty directory.
path- The directory to delete. Empty.
A missing or non-empty directory is an error, raised from the
FS effect’s fs-delete-directory.
See also: directory-delete-tree, file-delete, fs-delete-directory
directory-delete-tree
function ↑ Functions
(: directory-delete-tree (-> %p void))
(directory-delete-tree path)
Deletes a directory and everything under it.
path- The directory to delete.
Spelled differently from directory-delete because it is not a
mistake anything can undo.
It deletes one entry at a time through the FS operations, so a
handler sees every deletion. A symbolic link to a directory is removed as
a link and never entered, path itself included, so nothing a link
points at is deleted: a link to the home directory inside a build
directory leaves the home directory alone, and a link back up the tree
does not loop. A link that leads nowhere is removed as a file.
See also: directory-delete, directory-walk
directory-files
function ↑ Functions
(: directory-files (-> %p (Vec Path)))
(directory-files path)
The files directly in a directory.
path- The directory to list.
- returns
- Whole paths, in the order the OS lists them.
(vec-filter #(path-has-extension? &1 "bjo") (directory-files dir))
Directory listing does not accept a pattern glob; filter the returned
vector instead. An error listing is raised from the FS effect’s
fs-list.
See also: directory-subdirectories, directory-walk, Path
directory-subdirectories
function ↑ Functions
(: directory-subdirectories (-> %p (Vec Path)))
(directory-subdirectories path)
The directories directly in a directory.
path- The directory to list.
- returns
- Whole paths, in the order the OS lists them.
See also: directory-files, directory-walk
directory-walk
function ↑ Functions
(: directory-walk (-> %p (#:into? (-> Path bool)) (Seq Path)))
(directory-walk dir #:into? (fun (d) #t))
The files under a directory, depth first, pulled lazily.
dir- The directory to walk.
#:into?- Asked about each directory below dir before the walk enters it. By default every one is entered.
- returns
- A sequence of whole paths to files; directories themselves are not in it.
(filter #(path-has-extension? & "bjo")
(directory-walk "." #:into? (fun (d) (not (path-has-name? d ".git")))))
(find #(path-has-extension? & "bjo") (directory-walk ".")) ; stops at the first
Each directory’s entries come in the order of their names, byte by byte, so a walk is the same on every OS and on a fake filesystem. A directory that is a symbolic link is never entered, so a link back up the tree cannot loop the walk. An entry gone between listing and visiting is skipped.
Nothing is listed until the sequence is walked, using whatever FS
handler is active during traversal. Stopping early avoids reading further
entries. An error listing a directory is raised, as directory-files
raises it. A seq body cannot await, so a bjoroutine pulling from it
parks its thread on each pull.
See also: directory-files, directory-delete-tree, Path
fs-info
function ↑ Functions
(: fs-info (-> Path (Option FsInfo)))
The FS operation that queries metadata for a path.
path- The path to ask about.
- returns
- None when the path names nothing.
An operation of the FS effect: it calls the handler installed for
it, fs-info/raw when none is. Install one with
(with-handler ((fs-info (fun (path) ...))) body ...), which needs
(import (std effect)). file-info, file-exists?,
directory-exists? and the directory functions ask through it.
Every operation of the FS effect takes a Path, and a
handler gets the bytes of the path it was given. The functions that call
the operations take any value of AsPath and convert it.
See also: file-info, FsInfo, op/fs-info, fs-info/raw
fs-info/raw
function ↑ Functions
(: fs-info/raw (-> Path (Option FsInfo)))
(fs-info/raw path)
What the real file system says a path names, bypassing any FS handler.
path- The path to ask about.
- returns
- None when the path names nothing, or is no path at all.
The default handler of fs-info, and what a handler that wants to
fall through to the disk calls. A symbolic link’s size and time are those
of the end of its chain of links, followed for at most 40 steps; a link to
nothing keeps its own.
The /raw operations give a path to .NET as a string, which
must be UTF-8. For a path that is not UTF-8, they return an
ArgumentException, and this one raises it, because
None would say that nothing is there.
fs-list
function ↑ Functions
(: fs-list (-> Path (Result Exception (Vec FsEntry))))
The FS operation that lists a directory.
dir- The directory to list.
- returns
- The entries, files and directories and links, each with its kind, or the error listing it.
An operation of the FS effect: it calls the handler installed for
it, fs-list/raw when none is. directory-files,
directory-subdirectories, directory-walk,
directory-delete-tree and (std glob) list through it.
A handler reports the kind of each entry, as a listing of the OS does,
so these functions ask fs-info only about links.
See also: FsEntry, directory-files, directory-walk, op/fs-list, fs-list/raw
fs-list/raw
function ↑ Functions
(: fs-list/raw (-> Path (Result Exception (Vec FsEntry))))
(fs-list/raw path)
The entries of a directory on the real file system, bypassing any FS handler.
path- The directory to list.
- returns
- The entries, in the order the OS gives them, or the exception: DirectoryNotFoundException, UnauthorizedAccessException or IOException.
On Linux and Android it reads the directory with readdir: the
path and the names are bytes, so a name that is not UTF-8 is listed as
it is, and the kinds come from the listing, with no stat for an
entry. Elsewhere it uses .NET, with one stat for each entry, and
a name is what .NET decodes.
fs-create-directory
function ↑ Functions
(: fs-create-directory (-> Path (Result Exception Unit)))
The FS operation that creates a directory and every missing one along its path.
dir- The directory to create.
- returns
- Ok when it is there afterwards, or the error.
An operation of the FS effect: it calls the handler installed for
it, fs-create-directory/raw when none is.
See also: directory-create, op/fs-create-directory, fs-create-directory/raw
fs-create-directory/raw
function ↑ Functions
(: fs-create-directory/raw (-> Path (Result Exception Unit)))
(fs-create-directory/raw path)
Creates a directory on the real file system, bypassing any FS handler.
path- The directory to create.
- returns
- Ok, or the exception .NET raised.
Every missing directory along the path is created, and one that is already there is not an error.
See also: fs-create-directory
fs-delete-file
function ↑ Functions
(: fs-delete-file (-> Path (Result Exception Unit)))
The FS operation that deletes a file.
path- The file to delete.
- returns
- Ok, or the error.
An operation of the FS effect: it calls the handler installed for
it, fs-delete-file/raw when none is.
See also: file-delete, op/fs-delete-file, fs-delete-file/raw
fs-delete-file/raw
function ↑ Functions
(: fs-delete-file/raw (-> Path (Result Exception Unit)))
(fs-delete-file/raw path)
Deletes a file on the real file system, bypassing any FS handler.
path- The file to delete.
- returns
- Ok, also when the file is missing, or the exception .NET raised.
See also: fs-delete-file
fs-delete-directory
function ↑ Functions
(: fs-delete-directory (-> Path (Result Exception Unit)))
The FS operation that deletes an empty directory.
dir- The directory to delete.
- returns
- Ok, or the error.
An operation of the FS effect: it calls the handler installed for
it, fs-delete-directory/raw when none is.
See also: directory-delete, op/fs-delete-directory, fs-delete-directory/raw
fs-delete-directory/raw
function ↑ Functions
(: fs-delete-directory/raw (-> Path (Result Exception Unit)))
(fs-delete-directory/raw path)
Deletes an empty directory on the real file system, bypassing any FS handler.
path- The directory to delete.
- returns
- Ok, or the exception .NET raised: a missing or non-empty directory is an IOException.
See also: fs-delete-directory
fs-move
function ↑ Functions
(: fs-move (-> Path Path MoveMode (Result Exception Unit)))
The FS operation that moves or renames a file or a directory.
from- What to move.
to- Its new path.
mode- What to do when something is already there.
- returns
- Ok, or the error.
An operation of the FS effect: it calls the handler installed for
it, fs-move/raw when none is. file-move moves through it,
and file-copy with Truncate replaces its target with it.
See also: file-move, MoveMode, op/fs-move, fs-move/raw
fs-move/raw
function ↑ Functions
(: fs-move/raw (-> Path Path MoveMode (Result Exception Unit)))
(fs-move/raw from to mode)
Moves a file or a directory on the real file system, bypassing any FS handler.
from- What to move.
to- Its new path.
mode- Whether a file at to is replaced. Ignored for a directory, which never replaces.
- returns
- Ok, or the exception .NET raised.
get-environment-variable
function ↑ Functions
(: get-environment-variable (-> string (Option string)))
(get-environment-variable name)
The value of an environment variable of this process.
name- The variable's name.
- returns
- None when it is not set, or set to the empty string.
Follows R7RS naming, returning None where R7RS returns #f.
What it cannot tell apart is a variable that is unset and one set to
nothing. It reads the real environment directly; getenv asks
through a handler a test can replace.
See also: set-environment-variable!, getenv
set-environment-variable!
function ↑ Functions
(: set-environment-variable! (-> string string void))
(set-environment-variable! name value)
Sets an environment variable for this process and the processes it starts.
name- The variable's name.
value- Its new value. The empty string removes it.
Not for the shell that started the process.
See also: get-environment-variable
current-directory
function ↑ Functions
(: current-directory (-> string))
(current-directory)
The process’s current directory, which relative paths are resolved against.
- returns
- Its full path.
A function rather than a value, because it is process-wide mutable state.
See also: set-current-directory!, path-absolute
set-current-directory!
function ↑ Functions
(: set-current-directory! (-> %p void))
(set-current-directory! path)
Changes the process’s current directory.
path- The new current directory.
Process-wide: every thread and fiber resolves relative paths against it from then on.
See also: current-directory
getenv
function ↑ Functions
(: getenv (-> string (Option string)))
The Env operation that reads an environment variable.
name- The variable's name.
- returns
- None when it is not set.
(with-handler ((getenv (fun (name) (if (= name "HOME") (Some "/tmp/home") None))))
(run-the-thing))
An operation of the Env effect, allowing tests to mock environment
variables without modifying the process environment. With no handler
installed it is get-environment-variable. Installing one needs
(import (std effect)).
See also: get-environment-variable, op/getenv
display
function ↑ Functions
(: display (-> string void))
Writes a string to the current output port.
s- The text, written as it is, with no newline after it.
Writes to whatever current-output-port is bound to. It takes a
string; print takes any value, through displayed.
See also: displayln, newline, print, current-output-port, write-string
displayln
function ↑ Functions
(: displayln (-> string void))
Writes a string and a newline to the current output port.
s- The text, followed by the port's line terminator.
newline
function ↑ Functions
(: newline (-> void))
Writes a newline to the current output port.
The port’s line terminator, which for standard output is the platform’s.
See also: displayln, current-output-port
open-input-file
function ↑ Functions
(: open-input-file (-> %p (Result Exception InputPort)))
(open-input-file path)
Opens a file for reading.
path- The file.
- returns
- The port, or Err with the .NET exception when the file cannot be opened.
(match (open-input-file "notes.txt")
((Ok p) (read-all p))
((Err (:is System.IO.FileNotFoundException)) "")
((Err e) (raise e)))
A missing file is expected, so it is a Result rather than a
raise. The Err carries the real exception, so an arm can test
for System.IO.FileNotFoundException.
The file is opened through the open-read-stream operation, so a
handler of the FS effect intercepts it. The port is owned by the
ambient scope: when the scope returns, the file is closed, whether the
program closed it or not. The scope is read before the file is opened,
so a program with no scope fails without having opened anything.
The port’s text reads decode UTF-8; see InputPort for invalid
bytes, and for reading a file in another encoding.
See also: call-with-input-file, open-input-file/raw, open-read-stream, close-input-port, read-all
open-input-file/raw
function ↑ Functions
(: open-input-file/raw (-> %p (Result Exception InputPort)))
(open-input-file/raw path)
Opens a file for reading, past any FS handler.
path- The file.
- returns
- The port, or Err with the .NET exception.
open-input-file over open-read-stream/raw: the real
filesystem whatever handler is installed. What a fake filesystem calls
to fall through to the disk. The port is owned by the ambient scope.
See also: open-input-file, open-read-stream/raw
open-output-file
function ↑ Functions
(: open-output-file (-> %p (#:mode WriteMode) (Result Exception OutputPort)))
(open-output-file path #:mode Truncate)
Opens a file for writing.
path- The file.
#:mode- How: Truncate, the default, Append or CreateNew.
- returns
- The port, or Err with the .NET exception when the file cannot be opened.
(open-output-file "log.txt" #:mode Append)
The file is opened through the open-write-stream operation, so a
handler of the FS effect intercepts it. The port is owned by the
ambient scope and closed when the scope returns.
What is written is buffered. Closing flushes, but synchronously:
flush-port before the close lets a bjoroutine suspend on the
write instead.
See also: call-with-output-file, WriteMode, open-output-file/raw, open-write-stream, close-output-port
open-output-file/raw
function ↑ Functions
(: open-output-file/raw (-> %p WriteMode (Result Exception OutputPort)))
(open-output-file/raw path mode)
Opens a file for writing, past any FS handler.
path- The file.
mode- Truncate, Append or CreateNew.
- returns
- The port, or Err with the .NET exception.
open-output-file over open-write-stream/raw: the real
filesystem whatever handler is installed. The mode is positional here.
The port is owned by the ambient scope.
See also: open-output-file, open-write-stream/raw, WriteMode
open-input-string
function ↑ Functions
(: open-input-string (-> string InputPort))
(open-input-string contents)
A string as an input port.
contents- The text the port reads.
- returns
- The port. It cannot fail, so there is no Result.
(read-line (open-input-string "one\ntwo")) ; "one"
Memory only, so no scope owns it. Its reads never suspend, in either colour.
See also: open-output-string, open-input-file
open-output-string
function ↑ Functions
(: open-output-string (-> OutputPort))
(open-output-string)
A port that collects what is written to it.
- returns
- The output port. Call
get-output-stringto retrieve accumulated text.
Memory only, so no scope owns it. To build a string, prefer a
StringBuilder: writing to a port carries a colour, so a function
that writes to one gets a suspending copy, where a builder keeps it an
ordinary function.
See also: get-output-string, open-input-string
get-output-string
function ↑ Functions
(: get-output-string (-> OutputPort string))
(get-output-string p)
Everything written to a string port so far.
p- A port from open-output-string.
- returns
- The text collected. The port stays open and keeps collecting.
- raises
System.InvalidOperationException - When p is not a port from open-output-string.
(def out (open-output-string))
(write-string out "a")
(get-output-string out) ; "a"
(write-string out "b")
(get-output-string out) ; "ab"
Bytes written with write-bytes! that are not UTF-8 read as U+FFFD,
as Racket’s get-output-string reads them; get-output-bytes
has them as they are.
See also: open-output-string, writer->string
get-output-bytes
function ↑ Functions
(: get-output-bytes (-> OutputPort (Array byte)))
(get-output-bytes p)
Everything written to a string port so far, as bytes.
p- A port from open-output-string.
- returns
- A copy of the bytes collected: text as UTF-8, and bytes as they were written.
- raises
System.InvalidOperationException - When p is not a port from open-output-string.
(def out (open-output-string))
(write-string out "å")
(get-output-bytes out) ; #[195 165]
See also: get-output-string, open-output-string
close-input-port
function ↑ Functions
(: close-input-port (-> InputPort void))
(close-input-port p)
Closes an input port.
p- The port.
Rarely needed: with-open closes a port however the body ends, and
the scope that owns a file port closes it when it returns.
A port a scope owns is released through its registration, so the scope’s list does not keep a spent entry. A port nothing owns, such as a string port, is disposed. Standard input is never closed.
See also: close-output-port, call-with-input-file
close-output-port
function ↑ Functions
(: close-output-port (-> OutputPort void))
(close-output-port p)
Flushes and closes an output port.
p- The port.
Rarely needed: with-open closes a port however the body ends, and
the scope that owns a file port closes it when it returns.
A port a scope owns is released through its registration, and its
buffered text is written before the file is closed. That flush is
synchronous; call flush-port first for one a bjoroutine suspends
on. A port nothing owns is disposed. On standard output or standard
error it flushes and stops: nothing can take them away from the rest of
the program.
See also: close-input-port, flush-port, call-with-output-file
call-with-input-file
function ↑ Functions
(: call-with-input-file (-> %p (-?-> InputPort %a) (Result Exception %a)))
(call-with-input-file path proc)
Opens a file, hands the port to a function, and closes it.
path- The file.
proc- What to do with the port. Either colour.
- returns
- Ok containing proc's return value, or Err when the file cannot be opened.
(call-with-input-file "notes.txt" read-all)
The port is closed however proc ends, through its registration,
so the scope’s list is back to the length it had. An exception from
proc is raised, not put in the Err.
See also: open-input-file, call-with-output-file
call-with-output-file
function ↑ Functions
(: call-with-output-file (-> %p (-?-> OutputPort %a) (#:mode WriteMode) (Result Exception %a)))
(call-with-output-file path proc #:mode Truncate)
Opens a file for writing, hands the port to a function, and closes it.
path- The file.
proc- What to do with the port. Either colour.
#:mode- How the file is opened, as for open-output-file: Truncate by default.
- returns
- Ok containing proc's return value, or Err when the file cannot be opened.
(call-with-output-file "out.txt"
(fun (p) (writeln p "hello")))
The port is closed however proc ends, which writes what is still
buffered. An exception from proc is raised, not put in the
Err.
See also: open-output-file, call-with-input-file, WriteMode
port-eof?
function ↑ Functions
(: port-eof? (-> InputPort bool))
(port-eof? p)
Whether a port has no more input.
p- The port.
- returns
- #t at end of input. Asking consumes nothing.
On a file port, or standard input, it checks the buffer directly whenever the buffer holds anything, and reads ahead only when it is empty. That read suspends in a bjoroutine.
See also: read-line, read-line/opt, read-char/opt
read-line
function ↑ Functions
(: read-line (-> InputPort (#:mode LineMode) string))
(read-line p #:mode Any)
The next line of a port, without its line terminator.
p- The port. Not at end of input.
#:mode- What ends a line: Any, the default, AnyOne, Linefeed, Return or ReturnLinefeed.
- returns
- The line. A line at the end of input needs no terminator.
- raises
System.IO.EndOfStreamException - When the port is at end of input.
(let loop ()
(unless (port-eof? p)
(displayln (read-line p))
(loop)))
(read-line p #:mode Linefeed) ; a \\r stays in the line
The keyword makes read-line a function of two arguments where it
is passed as a value, so a reader that takes one is handed
(fun (p) (read-line p)).
See also: read-line/opt, LineMode, port-eof?, read-all, in-port
read-line/opt
function ↑ Functions
(: read-line/opt (-> InputPort (#:mode LineMode) (Option string)))
(read-line/opt p #:mode Any)
The next line of a port, or None at end of input.
p- The port.
#:mode- What ends a line, as for read-line: Any by default.
- returns
- Some line without its terminator, or None at end of input.
(when-let (line (read-line/opt port))
(displayln line))
One read. Where two fibers share a port, this is the way to read it to
the end: port-eof? followed by read-line is two, and the
other fiber can take the last line between them.
Passed as a value, it is (fun (p) (read-line/opt p)), for the
reason read-line is.
read-char
function ↑ Functions
(: read-char (-> InputPort char))
(read-char p)
The next character of a port.
p- The port. Not at end of input.
- returns
- The character: a Unicode scalar, so one outside the BMP is one char.
- raises
System.IO.EndOfStreamException - When the port is at end of input.
- raises
System.InvalidOperationException - When a .NET caller's UTF-16 read has left half a character behind.
Decodes one character of UTF-8 from the port’s bytes, however many bytes
it takes, so reading a port a character at a time agrees with
read-all walked as a string. An invalid sequence reads as
U+FFFD.
The InvalidOperationException can only follow a .NET API’s own reads of
the port as a TextReader, which hand out a character above the
BMP as two UTF-16 units: after the first of them, the next read is half
a character.
See also: read-char/opt, write-char, port-eof?
read-char/opt
function ↑ Functions
(: read-char/opt (-> InputPort (Option char)))
(read-char/opt p)
The next character of a port, or None at end of input.
p- The port.
- returns
- Some character, or None at end of input.
- raises
System.InvalidOperationException - When the port holds a surrogate that is not half of a pair.
One read, for the reason read-line/opt is. A character outside
the BMP is taken whole, so two fibers reading one port never split it.
See also: read-char, in-port
peek-char
function ↑ Functions
(: peek-char (-> InputPort char))
(peek-char p)
The next character of a port, left in the port.
p- The port. Not at end of input.
- returns
- The character read-char would answer.
- raises
System.IO.EndOfStreamException - When the port is at end of input.
- raises
System.InvalidOperationException - When a .NET caller's UTF-16 read has left half a character behind.
(def p (open-input-string "ab"))
(peek-char p) ; #\\a
(read-char p) ; #\\a
(peek-char p) ; #\\b
As Racket’s peek-char. Decoded from the port’s buffer like
read-char, waiting for as many bytes as the character needs,
and taking none of them: the next read, of characters or of bytes,
starts at the same place. An invalid sequence peeks as U+FFFD.
A peek and the read after it are two operations: another fiber reading the same port can take the character between them.
See also: peek-char/opt, read-char
peek-char/opt
function ↑ Functions
(: peek-char/opt (-> InputPort (Option char)))
(peek-char/opt p)
The next character of a port, left in the port, or None at end of input.
p- The port.
- returns
- Some character, or None at end of input.
- raises
System.InvalidOperationException - When the port holds a surrogate that is not half of a pair.
See also: peek-char, read-char/opt
read-all
function ↑ Functions
(: read-all (-> InputPort string))
(read-all p)
Everything left in a port, as one string.
p- The port.
- returns
- The rest of the input. Empty at end of input.
port-fold
function ↑ Functions
(: port-fold (-> (-?-> InputPort %a %a) %a InputPort %a))
(port-fold f init port)
Folds a reading function over a port until it is out.
f- Called with (port, acc) while there is input; reads from port and returns the new accumulator value. Either colour.
init- The first accumulator.
port- The port.
- returns
- The accumulator once the port is at end of input.
(port-fold (fun (p n) (ignore (read-line p)) (+ n 1)) 0 port) ; lines left
f is called only when port-eof? says there is more, and
decides how much one step reads. A suspending f makes the fold
suspend, so it is the way to read a port element by element in a
bjoroutine.
write-string
function ↑ Functions
(: write-string (-> OutputPort string void))
(write-string p s)
Writes a string to a port.
p- The port.
s- The text, written as it is.
The port comes first, as for every port operation. A file port buffers the text, so it reaches the file at a flush, a close, or when the buffer fills; in a bjoroutine a write that fills the buffer suspends on the drain.
See also: writeln, write-char, flush-port, display
writeln
function ↑ Functions
(: writeln (-> OutputPort string void))
(writeln p s)
Writes a string and a newline to a port.
p- The port.
s- The text, followed by the port's line terminator.
See also: write-string, displayln
write-char
function ↑ Functions
(: write-char (-> OutputPort char void))
(write-char p c)
Writes one character to a port.
p- The port.
c- The character. One outside the BMP is written as both of its UTF-16 units.
See also: read-char, write-string
flush-port
function ↑ Functions
(: flush-port (-> OutputPort void))
(flush-port p)
Writes what a port has buffered to where it goes.
p- The port.
In a bjoroutine it suspends on the write. Closing a port flushes too, but synchronously, so flush first where waiting should not block a thread.
See also: close-output-port, write-string
reader-read-line!
function ↑ Functions
(: reader-read-line! (-> Bjolang.Runtime.BjoInputPort string))
The next line of a reader, blocking until it is read.
r- The reader. Not at end of input.
- returns
- The line, without its line terminator.
- raises
System.IO.EndOfStreamException - When the reader is at end of input.
A runtime primitive that only blocks; it has no suspending copy.
read-line is the same read in both colours, and is what a
program calls.
See also: read-line, read-line/opt
reader-read-char!
function ↑ Functions
(: reader-read-char! (-> Bjolang.Runtime.BjoInputPort char))
The next character of a reader, blocking until it is read.
r- The reader. Not at end of input.
- returns
- The character, with a surrogate pair put back together.
- raises
System.IO.EndOfStreamException - When the reader is at end of input.
- raises
System.InvalidOperationException - When the reader holds a surrogate that is not half of a pair.
A runtime primitive that only blocks; it has no suspending copy.
read-char is the same read in both colours, and is what a
program calls.
See also: read-char, read-char/opt
writer-write-char!
function ↑ Functions
(: writer-write-char! (-> Bjolang.Runtime.BjoOutputPort char void))
Writes one character to a writer.
w- The writer.
c- The character. One outside the BMP is written as both of its UTF-16 units.
A runtime primitive with no suspending copy. write-char is the
same write in both colours, and is what a program calls.
See also: write-char
writer->string
function ↑ Functions
(: writer->string (-> Bjolang.Runtime.BjoOutputPort string))
What a string writer has collected.
w- A writer from open-output-string.
- returns
- The text written to it so far.
- raises
System.InvalidOperationException - When w is not a string writer.
What get-output-string is built on. It raises rather than returning
the writer’s type name, which is what .NET’s ToString would give
for a file port.
See also: get-output-string
open-read-stream
function ↑ Functions
(: open-read-stream (-> Path (Result Exception ClrStream)))
Opens a file as a stream for reading: an operation of the FS effect.
path- The path.
- returns
- The stream, or Err with the exception.
Everything in the prelude and (std ports) that reads a file opens
it through this, so a handler installed with with-handler intercepts
all reads: a test reads from a fake, a sandbox refuses. With no
handler it falls back to open-read-stream/raw.
Returns a ClrStream, not a port. open-input-file builds the
port over it and registers it on the ambient scope, so a
MemoryStream a handler made is owned exactly as a file is.
See also: open-read-stream/raw, op/open-read-stream, open-input-file, open-write-stream
open-write-stream
function ↑ Functions
(: open-write-stream (-> Path WriteMode (Result Exception ClrStream)))
Opens a file as a stream for writing: an operation of the FS effect.
path- The path.
mode- How the file is opened.
- returns
- The stream, or Err with the exception.
Everything in the prelude and (std ports) that writes a file
opens it through this, so an installed handler intercepts all writes.
With no handler it falls back to open-write-stream/raw.
Returns a ClrStream, not a port. open-output-file builds
the port over it and registers it on the ambient scope.
See also: open-write-stream/raw, op/open-write-stream, open-output-file, WriteMode
open-read-stream/raw
function ↑ Functions
(: open-read-stream/raw (-> Path (Result Exception ClrStream)))
(open-read-stream/raw path)
Opens a file on disk as a stream for reading, past any handler.
path- The file.
- returns
- The stream, or Err with an IOException or UnauthorizedAccessException.
The default handler of open-read-stream. Read-only, with other
readers allowed alongside. A missing file is a
FileNotFoundException, which is an IOException.
See also: open-read-stream, open-input-file/raw
open-write-stream/raw
function ↑ Functions
(: open-write-stream/raw (-> Path WriteMode (Result Exception ClrStream)))
(open-write-stream/raw path mode)
Opens a file on disk as a stream for writing, past any handler.
path- The file.
mode- Truncate, Append or CreateNew.
- returns
- The stream, or Err with an IOException or UnauthorizedAccessException.
The default handler of open-write-stream. Write-only, with
readers allowed alongside. CreateNew on a file that exists is an
IOException.
See also: open-write-stream, open-output-file/raw, WriteMode
warn
function ↑ Functions
(: warn (-> string void))
Reports that something is wrong, and carries on: an operation of the Diagnostics effect.
message- The message.
(warn "config.toml not found; using defaults")
By default it writes the message as a line on current-error-port.
A handler installed with with-handler decides otherwise: collect
the warnings, count them, or raise to make them fatal.
It is synchronous on purpose, so that an ordinary function can warn. A
handler that wants to hand the line to a channel puts it on a mutable
queue rather than syncing.
See also: log, op/warn, current-error-port
log
function ↑ Functions
(: log (-> string void))
A line of diagnostics: an operation of the Diagnostics effect.
message- The line.
(with-handler ((log (let ((outer (handler-of log)))
(fun (s) (outer (str "[app] " s))))))
(log "started"))
By default it writes the line on current-error-port. A handler
installed with with-handler sends it elsewhere. A handler that
calls log calls itself; (handler-of log) is the one
installed before it.
Synchronous, like warn, so an ordinary function can log. The
natural logarithm is loge, in (std maths).
See also: warn, op/log, current-error-port
sync
function ↑ Functions
(: sync (-bjo-> (Event %a) %a))
Synchronizes on an event and returns its value: the yield point of a bjoroutine.
ev- The event to wait for. Any event: a channel operation, a choose, a timeout, a promise's join.
- returns
- The value of the event that committed.
- raises
Bjolang.Runtime.Cancelled - When the ambient token fires before the event commits.
(sync (chan-recv jobs))
(sync (choose (chan-recv a) (chan-recv b)))
Building an event never suspends; only sync does, so only a
bjoroutine may write it. The other yield points are calls to bjoroutines
(chan-put, chan-get, the scope forms, an #:async
.NET call), and a fiber may resume on a different thread after any of
them. Other fibers run on other threads at the same time: nothing gives a
fiber exclusive access to state it shares with another, even between two
syncs, so shared state is passed on a channel or guarded, as it would be
between threads.
Every sync watches the ambient token, current-cancel: once
the scope it runs in has been cancelled, the sync raises instead of
waiting. An event that is ready at the sync still commits, since the token
is offered after the event’s own branches and a cancellation never undoes
a commit. Code that has to wait after a cancellation, such as cleanup,
runs inside with-shield.
A plain defun cannot write it. sync/blocking is the same
wait for an ordinary function, parking the calling thread.
See also: sync/blocking, choose, chan-get, chan-put, current-cancel
sync/blocking
function ↑ Functions
(: sync/blocking (-> (Event %a) %a))
Waits for an event from an ordinary function, parking the calling thread.
ev- The event to wait for.
- returns
- The value of the event that committed.
- raises
Bjolang.Runtime.Cancelled - When the ambient token fires first, raised on the calling thread.
(sync/blocking (chan-recv ch))
(sync/blocking (promise-join (bjo (work 21))))
(sync/blocking (choose (wrap (chan-recv ch) (fun (v) (Got v)))
(wrap (timeout (seconds 1)) (fun (u) TimedOut))))
No fiber is spawned. It is the mirror of blocking: that one carries
a thread-parking call into fiber-land, this one carries an event out.
Do not call it from inside a bjoroutine. It parks the thread it is
called on, and inside a fiber that thread belongs to the pool, which is
what the events being waited for need in order to fire. Use sync
instead.
Nothing withdraws it once parked. A wait that might not end needs
its own way out composed in first, as with the timeout above. The
ambient token is offered as one more branch, as sync offers it.
See also: sync, blocking, promise-join/sync
make-chan
function ↑ Functions
(: make-chan (-> (Chan %a)))
A new synchronous, unbuffered channel.
- returns
- A channel on which a send and a receive meet.
A rendezvous: neither a send nor a receive completes until the other arrives, which is where backpressure comes from.
A channel has no close. A producer that has to say it is finished hands
over a promise beside the channel, as async-seq->chan does.
Waiting operations on a contended channel are not guaranteed to be served in the order they arrived.
chan-send
function ↑ Functions
(: chan-send (-> (Chan %a) %a (Event void)))
The event of handing a value over a channel.
ch- The channel.
v- The value to hand over.
- returns
- An event that commits when a receiver takes v.
Not the handing over: that happens at the sync. Building the event
does nothing to the channel, and a send that loses a choose is
withdrawn, so v is never delivered.
(sync (chan-send ch v)) is (chan-put ch v), which builds no
event value. The compiler emits it as chan-put when it is written
that way. A send event that gets to sync in another way, for
example in a variable, is built.
chan-recv
function ↑ Functions
(: chan-recv (-> (Chan %a) (Event %a)))
The event of taking one message off a channel.
ch- The channel.
- returns
- An event whose value is the message taken.
A receive that loses a choose is removed from the channel, so
nothing is left waiting for a message that will never be read.
(sync (chan-recv ch)) is (chan-get ch).
chan-put
function ↑ Functions
(: chan-put (-bjo-> (Chan %a) %a void))
Hands a value over a channel, and returns when it has been taken.
ch- The channel.
v- The value to hand over.
- raises
Bjolang.Runtime.Cancelled - When the ambient token fires before a receiver takes v.
(sync (chan-send ch v)) without the event value in between, as in
Guile’s put-message beside its put-operation. It waits and is
cancelled exactly as sync is. The event form is for what an event is
for: choose, wrap, and passing one around.
chan-get
function ↑ Functions
(: chan-get (-bjo-> (Chan %a) %a))
Takes one message off a channel, waiting for a sender.
ch- The channel.
- returns
- The message.
- raises
Bjolang.Runtime.Cancelled - When the ambient token fires before a sender arrives.
(sync (chan-recv ch)) in one call. It waits and is cancelled exactly
as sync is.
async-seq->chan
function ↑ Functions
(: async-seq->chan (-> (AsyncSeq %a) (Tuple (Chan %a) (Promise void))))
A .NET async stream as a channel, and a promise that it is over.
s- The stream, an
IAsyncEnumerable. - returns
- A tuple of the channel the items arrive on and a promise that lands when the stream has ended or failed.
An async stream can only be walked. A channel can go into a choose,
be raced against a timeout and be withdrawn, so a fiber pumps the one
into the other. The pump belongs to the scope that asked for the stream
as a spawn/daemon does: the scope does not wait for it, and when
the scope ends the pump stops, even in the middle of a send nobody takes,
and the promise fails with Cancelled.
The channel is synchronous, so the pump waits in the rendezvous until a receiver takes each item: a slow consumer stops the producer rather than growing a buffer. For the same reason the pump cannot finish until its last item was taken, so when the promise lands the channel is empty, and a consumer choosing between the two branches never has to guess.
The promise is there because a channel has no close, and a close could not say why the stream ended. A stream that throws fails the promise.
A stream that stalls while producing an item stalls the pump with it: the token is the stream’s to honour.
See also: make-chan, promise-join, choose
choose
function ↑ Functions
(: choose (-> (Array (Event %a)) (Event %a)))
An event that offers several and commits to exactly one.
evs ...- The events to offer.
- returns
- An event whose value is the value of whichever event committed.
(sync (choose (wrap (chan-recv results) #(Some &))
(wrap (timeout (milliseconds 20)) (fun (u) None))))
The losers are withdrawn, not merely ignored: a losing receive is taken off its channel and a losing send never delivers.
Order is priority. When several branches are ready at the sync, the first one written wins, every time. A loop that chooses between two busy channels can therefore starve the second.
An event that is always ready, such as always, a promise that has
landed or a token that has fired, wins every iteration of a loop it is
offered in.
wrap
function ↑ Functions
(: wrap (-> (Event %a) (-> %a %b) (Event %b)))
An event that applies a function to another event’s value upon commit.
ev- The event.
f- What to apply to its value once it has committed.
- returns
- An event that commits when ev commits, yielding (f value).
(choose (wrap (chan-recv ch) (fun (v) (Got v)))
(wrap (timeout (seconds 1)) (fun (u) TimedOut)))
map for events, and the way branches of different types are brought
to one type for a choose. f runs after the commit, as the value is
delivered, so it does not decide whether its branch wins.
It runs on the fiber that synced, before sync returns, so it sees
that fiber’s parameterize bindings and handlers, and what it raises
is raised by the sync. The partner of a rendezvous has already gone
on by then, and the value is consumed whether f returns or raises.
There is no bind: a composite with two commit points could not be
withdrawn.
guard
function ↑ Functions
(: guard (-> (-> (Event %a)) (Event %a)))
An event built afresh at each sync.
thunk- Makes the event, called each time the guard is synced.
- returns
- The event constructed by thunk at synchronization time.
For an event that depends on the moment of synchronisation, or that has to acquire something only when it is actually offered. thunk runs when the sync publishes the event, not when the guard is built.
with-nack
function ↑ Functions
(: with-nack (-> (-> (Event void) (Event %a)) (Event %a)))
An event built with a second event that fires if it loses.
f- Function receiving the nack event and returning the event to synchronize.
- returns
- An event that is the branch f built, built afresh at each sync.
For a branch that acquires something which must be released if it does
not win: a timer, a cancellation source, a tentative reservation. Without
it, every losing choose leaks whatever the branch took.
The nack is a fact rather than a message: every listener sees it, and a late listener still does.
What reacts to the nack must not be ordinary work. Its callbacks run on a
borrowed thread; they may wake a fiber or fire a token, as
make-cancel’s thunk does, and nothing more.
always
function ↑ Functions
(: always (-> %a (Event %a)))
An event that is always ready, with the given value.
v- Its value.
- returns
- An event that commits at once with v.
Always ready, so it wins every iteration of a choose loop it is
offered in. That is the definition, and the same trap a landed promise
sets.
never
function ↑ Functions
(: never (-> (Event %a)))
An event that is never ready.
- returns
- An event that never commits.
The identity of choose, and what a branch returns when it has
nothing to offer. Synced on its own, only the ambient token firing
ends the wait.
timeout
function ↑ Functions
(: timeout (-> Duration (Event Unit)))
(timeout d)
An event that is ready a length of time after it is synced.
d- A Duration, counted from each sync. Zero or less is ready at once.
- returns
- An event that commits with unit when the time is up.
(sync (choose (wrap (chan-recv ch) #(Some &))
(wrap (timeout (seconds 5)) (fun (u) None))))
Relative to the sync, not to when the event was built, so one timeout value offered in a loop gives each iteration the full interval. A losing timeout’s timer is disposed.
For a budget over a whole loop, use at-time from (std datetime),
which is ready at an Instant.
See also: seconds, choose, with-deadline
promise-join
function ↑ Functions
(: promise-join (-> (Promise %a) (Event (Result System.Exception %a))))
The event of a promise landing, with its success or failure.
p- The promise, from
bjoorspawn-thunk. - returns
- An event whose value is
(Ok v), or(Err e)when the fiber raised e.
(match (sync (promise-join (bjo (fetch url))))
((Ok page) (use page))
((Err e) (log-failure e)))
Building the event does not wait; (sync (promise-join p)) does.
Failure is a value because “the fiber died” is a fact the joiner needs.
A promise is persistent: once it has landed, every sync of its join
commits immediately with the same value. A landed promise in a choose
loop wins every iteration.
See also: promise-join/sync, promise-done?, detach
promise-join/sync
function ↑ Functions
(: promise-join/sync (-> (Promise %a) %a))
(promise-join/sync p)
Waits synchronously for a promise and returns its value.
p- The promise.
- returns
- The promise's value. When the fiber raised, that exception is raised here.
- raises
Bjolang.Runtime.Cancelled - When the ambient token fires before the promise lands, as for
sync/blocking.
(sync/blocking (promise-join p)), with any failure re-raised
rather than returned as an Err. It parks the calling thread, so it is for ordinary
functions; a bjoroutine syncs on promise-join.
See also: promise-join, sync/blocking
promise-done?
function ↑ Functions
(: promise-done? (-> (Promise %a) bool))
Polls whether a promise has completed, without blocking.
p- The promise.
- returns
- #t once the promise has a value or a failure.
See also: promise-join
detach
function ↑ Functions
(: detach (-> (Promise %a) void))
Stops listening to a promise, deliberately.
p- The promise whose result is not wanted.
Dropping a promise loses any exception inside it silently. This says “I know, and I still do not want the result”, and a failure is reported to the scheduler’s unhandled-exception hook instead. A fiber that stopped because it was cancelled is not reported: that is how a worker normally ends.
(ignore p) on a promise is this.
See also: promise-join, spawn-thunk
spawn-thunk
function ↑ Functions
(: spawn-thunk (-> (-> %a) (Promise %a)))
Starts a thunk as a fiber of the current scope: bjo as a function.
f- The work. It runs to completion without suspending.
- returns
- A promise for the thunk's completion, identical to
bjo. - raises
Bjolang.Runtime.ScopeEnded - When there is no ambient scope.
(map spawn-thunk thunks)
bjo is a special form and not a value, so this is the spelling for
the higher-order case. The fiber goes into the current scope as
bjo’s does, and the scope waits for it.
A thunk has no yield point, so it cannot be cancelled: the scope waits for
it to finish, and a long one holds its scope open. Spawned into a scope
that has begun closing, it starts nothing and returns a promise that has
already failed with Cancelled.
See also: detach, promise-join, spawn/thread
current-dynamic-environment
function ↑ Functions
(: current-dynamic-environment (-> DynamicEnvironment))
Returns the dynamic environment here, for code that runs on another thread.
- returns
- The ports, the parameters, the ambient cancellation token and the scope of the caller.
(def env (current-dynamic-environment))
(sync (chan-send jobs (fun () (call-with-dynamic-environment env work))))
See also: call-with-dynamic-environment, blocking
call-with-dynamic-environment
function ↑ Functions
(: call-with-dynamic-environment (-> DynamicEnvironment (-> %a) %a))
Runs a thunk in a dynamic environment that was taken elsewhere.
env- The environment, from
current-dynamic-environment. thunk- Ordinary code: it cannot suspend.
- returns
- What thunk returns.
The thunk sees the parameters, the ports and the cancellation token of
the code that took env. The environment of the thread is put back
when the thunk returns or raises. This is what blocking and
spawn/thread do for their thunks, for code that hands work to
another thread itself, as the compute threads of (std parallel)
do.
Scopes. env holds the scope of the code that took it, and
a spawn in the thunk enlists there. When that scope has closed, a
spawn starts nothing, and bjo returns a promise that has
failed with Cancelled. The token of a closed scope has fired, so a
sync in the thunk raises Cancelled. Use it while the code
that took it waits.
See also: current-dynamic-environment
blocking
function ↑ Functions
(: blocking (-> (-> %a) (Event (Result System.Exception %a))))
An event that runs a thread-parking thunk off the fiber pool.
thunk- The work: a call that parks its thread, such as a synchronous read.
- returns
- An event whose value is
(Ok v), or(Err e)when thunk raised e.
(sync (blocking #(file-read-text path))) ; (Result Exception string)
File.ReadAllText, Console.ReadLine, Monitor.Enter:
each parks the thread it is called on, and in a fiber that is a pool
thread. This runs the thunk through Task.Run, on a thread the pool
can grow to replace, and the fiber suspends on the result.
Guarded, so each sync starts a fresh run rather than replaying the initial result. The thunk sees the dynamic environment of the sync.
Not cancellable. What cancellation reaches is the wait: a cancelled scope stops waiting while the thunk carries on to the end, and the scope does not wait for it either.
See also: spawn/thread, sync/blocking
spawn/thread
function ↑ Functions
(: spawn/thread (-> (-> %a) (Event (Result System.Exception %a))))
An event that runs a CPU-heavy thunk on a thread of its own.
thunk- The work: long computation.
- returns
- An event whose value is
(Ok v), or(Err e)when thunk raised e.
(sync (spawn/thread #(resize image 2048))) ; (Result Exception Image)
A function, not one of the spawn special forms, despite the name:
it is written (sync (spawn/thread #(crunch data))). The spawn forms
decide who owns a fiber; this decides where work runs.
blocking is for work that parks a thread, this for work that uses a
core. It asks .NET for a dedicated thread, which costs about a megabyte of
stack and is created and destroyed per call: worth it for work measured in
tens of milliseconds, a loss for work measured in microseconds.
Guarded, so each sync starts a fresh thread. Not cancellable: a cancelled scope stops waiting, the thread carries on to the end, and the scope does not wait for it.
See also: blocking, spawn-thunk
spawn-evt/start
function ↑ Functions
(: spawn-evt/start (-> (-> (Promise %a)) (Event (Result System.Exception %a))))
What (spawn-evt (f x)) becomes: start a fiber at the sync, cancel it if the branch loses.
start- A thunk holding the spawn.
- returns
- An event whose value is the fiber's
(Ok v)or(Err e).
The parser turns (spawn-evt (f x)) into a call of this over a
thunk holding the spawn. It is not meant to be called by hand.
At each sync the child is started under a cancellation token of its own,
not linked to the ambient one, installed as current-cancel around
the spawn so that the whole subtree inherits it. The child still goes
into the current scope, which waits for it. If the branch loses its choose, the token
fires with (Requested "spawn-evt: the branch lost its choose").
(promise-join (bjo (f x))), by contrast, starts eagerly and a lost
choose only stops the listening.
Cancellation is still cooperative: a child that never syncs runs to the end.
See also: promise-join, with-nack
make-cancel
function ↑ Functions
(: make-cancel (-> (Tuple (-> CancelReason void) CancelToken)))
A cancel thunk and the token it fires.
- returns
- A tuple: the thunk, which takes a reason and fires the token, and the token.
(def (Tuple cancel token) (make-cancel))
(spawn (worker token))
(cancel (Requested "shutdown"))
Two values because they are two rights: whoever holds the thunk can cancel, whoever holds the token can only notice. A worker handed the token can watch for its own end without being able to stop its siblings.
Cancelling twice does nothing, so the token carries the first reason it was given.
See also: cancelled, cancelled?, cancel-reason, link-cancel, with-cancel
cancelled
function ↑ Functions
(: cancelled (-> CancelToken (Event CancelReason)))
The event of a token having fired, carrying the reason.
token- The token.
- returns
- An event whose value is the reason the token was fired with.
(sync (choose (wrap (chan-recv jobs) #(Job &))
(wrap (cancelled token) #(Stop &))))
An event rather than a callback, so a token can be raced against real work. A token fires once and stays fired, so after it fires this commits at once at every sync: a loop that offers it has to leave when it wins.
See also: until-cancelled, cancelled?, choose
cancelled?
function ↑ Functions
(: cancelled? (-> CancelToken bool))
Polls whether a cancellation token has fired, without waiting.
token- The token.
- returns
- #t once it has fired.
The poll, for a compute loop with no sync to hang a choose
on. A loop that neither syncs nor checks runs to the end whoever cancelled
it.
See also: cancel-reason, cancelled
cancel-reason
function ↑ Functions
(: cancel-reason (-> CancelToken (Option CancelReason)))
Why a token fired, if it has.
token- The token.
- returns
(Some reason), orNonewhile it has not fired.
A loop tests with cancelled? and, having left, asks this what
cleanup it owes.
See also: cancelled?, Requested
until-cancelled
function ↑ Functions
(: until-cancelled (-> CancelToken (Event %a) (Event (Option %a))))
An event, or None if a token fires first.
token- A token other than the ambient one.
ev- The event.
- returns
- An event whose value is
(Some v)when ev commits, andNonewhen token has fired.
(match (sync (until-cancelled deadline (chan-recv jobs)))
((Some job) (handle job))
(None (give-up)))
For a per-request deadline, a sub-scope’s token, or one received from
elsewhere. None rather than a raise because a fired token stays
fired: a loop that raced one directly would win on it every iteration and
spin, and with None leaving is the natural spelling.
ev is offered first, so a token that has already fired does not take an iteration in which ev was ready.
Do not hand it the ambient token. sync already watches
that one, and the two would race: whichever commits first decides between
None and a raise.
link-cancel
function ↑ Functions
(: link-cancel (-> CancelToken CancelToken void))
Makes one token fire when another does.
parent- The token whose firing is passed on.
child- The token fired with the parent's reason.
One way only: firing the child says nothing to the parent. A tree of tokens is repeated linking, and a leaf that is cancelled cancels only what hangs below it.
See also: make-cancel
Requested
function ↑ Functions
(: Requested (-> string CancelReason))
A cancellation reason: someone asked to stop.
who- Who asked, or why. A diagnostic, not something to dispatch on.
- returns
- The reason.
The cancellation reasons are a closed set: Requested,
Deadline, Scope-Ended and Failed. A library cannot
add one, and Requested is the case for everything the other three
do not name.
See also: Deadline, Scope-Ended, Failed, make-cancel
Failed
function ↑ Functions
(: Failed (-> System.Exception CancelReason))
A cancellation reason: the scope’s body, or a child, raised.
e- The exception.
- returns
- The reason.
See also: with-cancel, Requested
current-scope
function ↑ Functions
(: current-scope (-> Scope))
The ambient scope, as a value.
- returns
- The innermost scope the caller is running in.
- raises
Bjolang.Runtime.ScopeEnded - When there is none: during module initialisation, or in a callback from .NET.
For in-scope, and for a callback that has to capture one. main
runs in a scope, so there is one everywhere else.
own!
function ↑ Functions
(: own! (-> (-> void) Owned))
Registers a release on the ambient scope.
thunk- What releases the resource. It runs once, when the scope closes or at release!.
- returns
- The handle that runs it early, through
release!. - raises
Bjolang.Runtime.ScopeEnded - When there is no ambient scope, or the scope has already run its releases.
(ignore (own! (fun () (release-the-permit))))
For what the GC cannot price: OS handles, permits, subscriptions, state that has to be put back. Not for memory.
Releases run when the scope closes, after every fiber it waits for has landed, newest first, with a fresh token installed so that they are not cancelled. A release that throws is recorded and the rest still run.
A release is a plain thunk: it cannot suspend and has no deadline, so one that blocks blocks the close.
A closing scope still accepts an own! until its releases have run,
so a child opening a file during the drain is covered. After that it
raises, since nothing would release the resource. A file opened in a
spawned fiber belongs to the enclosing scope, not to the fiber.
See also: release!, own-disposable, with-scope, in-scope
release!
function ↑ Functions
(: release! (-> Owned void))
Runs an owned release now, and takes it off its scope.
owned- The handle returned by
own!.
A second call does nothing, and so does one that lost the race with the scope’s own closing pass: the thunk runs exactly once either way. When it runs here, on the caller’s stack, its exception reaches the caller.
See also: own!
scope-open!
function ↑ Functions
(: scope-open! (-> long Scope))
A new scope linked to the ambient one. Internal to the scope forms.
ms- A deadline in milliseconds, or zero for none.
- returns
- The scope, not yet installed.
Cancelling the ambient token cancels this scope; this scope cancelling
itself says nothing to its parent. When ms is more than zero, a timer
fires the scope’s token with Deadline.
What with-scope and with-cancel expand to, through
scope-form; with-deadline opens the same scope with a
deadline that is always there. Not meant to be called directly: an
install needs a close that a finally guards.
See also: scope-form, with-cancel, shield-open!
shield-open!
function ↑ Functions
(: shield-open! (-> long Scope))
A new scope with no link to the ambient one. Internal to with-shield.
ms- A deadline in milliseconds, more than zero.
- returns
- The scope, not yet installed.
What with-shield expands to. Not meant to be called directly.
See also: with-shield, scope-open!
scope-push!
function ↑ Functions
(: scope-push! (-> Scope DynEnv))
Installs a scope as the ambient one, returning the displaced environment.
s- The scope.
- returns
- The environment to hand back to
dyn-restore!.
Binds the scope and current-cancel together, so that a
spawn and a sync inside it always mean the same
cancellation. What scope-form and in-scope expand to; not
meant to be called directly.
See also: dyn-restore!, scope-form, in-scope
scope-canceller
function ↑ Functions
(: scope-canceller (-> Scope (-> CancelReason void)))
The thunk that fires a scope’s token. Internal to the scope forms.
s- The scope.
- returns
- A function taking the reason to fire the token with.
What the cancel of with-cancel is bound to. Firing an
already fired token does nothing.
See also: scope-cancel!, with-cancel, make-cancel
scope-token
function ↑ Functions
(: scope-token (-> Scope CancelToken))
A scope’s cancellation token.
s- The scope.
- returns
- The token the scope installs as
current-cancel.
See also: current-scope, until-cancelled, cancel-reason
scope-close!
function ↑ Functions
(: scope-close! (-bjo-> Scope (Option System.Exception) void))
Ends a scope: waits for its children, releases what it owns, and reports. Internal to the scope forms.
s- The scope.
failure- The exception the body is leaving with, or
None.
With a failure, the token fires with (Failed e) first. Then the
scope is marked closing, and from then on a spawn into it starts nothing;
if a child had already failed, the token fires with that child’s
Failed now. It waits for every child without watching any token,
fires the token with Scope-Ended, stops the deadline timer, and
runs the releases newest first. Then it raises what the children and the
releases raised: one failure as itself, several, or any beside the
body’s, as one System.AggregateException. The body’s failure alone
is not raised here; scope-form raises it again.
What scope-form expands to; not meant to be called directly.
See also: scope-form, with-cancel
scope-close!/blocking
function ↑ Functions
(: scope-close!/blocking (-> Scope (Option System.Exception) void))
scope-close! for ordinary code: parks the thread until the scope has ended. Internal to the scope forms.
s- The scope.
failure- The exception the body is leaving with, or
None.
Does what scope-close! does, and parks the thread while it waits.
What scope-form expands to in a defun or a
(fun ...); not meant to be called directly.
See also: scope-close!, scope-form
scope-cancel!
function ↑ Functions
(: scope-cancel! (-> Scope CancelReason void))
Fires the token of a scope held as a value.
s- The scope.
reason- The reason to fire it with.
What the cancel thunk does. Firing an already fired token does nothing.
See also: scope-canceller, current-scope
scope-owned-count
function ↑ Functions
(: scope-owned-count (-> Scope int))
How many releases a scope still holds.
s- The scope.
- returns
- The number of handles registered and not yet released.
A test hook: std/simpletest fails a test that left one behind.
fiber-trace
function ↑ Functions
(: fiber-trace (-> string))
A report of every fiber that waits now: where it waits, on what, and in which scope.
- returns
- The report as text. When the trace is off, a line that tells how to turn it on.
(with-deadline (seconds 5)
(spawn (worker jobs))
(sync (timeout (seconds 1)))
(warn (fiber-trace)))
The trace is on when the environment variable BJO_FIBER_TRACE
is set, as in BJO_FIBER_TRACE=1 dotnet app.exe. When it is off,
the program runs the same code as before the trace existed: every hook
tests a value that the JIT reads as a constant. A Native AOT
executable has no trace: the build removes the hooks, because without
a JIT the test costs time. There fiber-trace answers a line
that says so; run the .exe built beside it to get the trace.
The report puts each fiber under the scope it waits in, with the scopes
in a tree. For each fiber it gives what the fiber waits on
(waiting in chan-recv on channel #1, waiting for a timeout,
waiting in a choose, closing this scope, waiting for its
children), how long it has waited, the
line of the sync, and the lines of the bjoroutines that called
it. Fibers that wait at the same place are counted together. A thread
that waits in sync/blocking or at the close of a scope is in
the report too.
With the trace on, the program also writes the report to standard error
when it gets SIGQUIT (Ctrl-\ in a terminal), and once when it looks
deadlocked: nothing has run for two seconds, and every fiber waits on a
channel, a fiber or the close of a scope. A wait on a timer, a
choose or a .NET task can end without help from a fiber, so then
nothing is written.
The trace costs time when it is on: each wait records a frame, and the first wait at each line reads the stack. Use it to find where a program is stuck, not in production.
See also: with-deadline, with-cancel, sync
dyn-restore!
function ↑ Functions
(: dyn-restore! (-> DynEnv void))
Puts back a dynamic environment saved earlier. Internal to the forms that bind one.
env- The environment returned by
scope-push!or parameter push.
The other half of scope-push!, and of the push
parameterize expands to. scope-form, in-scope and
parameterize call it in a finally. Not meant to be called
directly.
See also: scope-push!, in-scope, scope-form
close-owned-or-dispose
function ↑ Functions
(: close-owned-or-dispose (-> %a void))
Closes what a with-open bound: through its owner if a scope owns it, by disposing it if not.
x- The value the binding held.
The exit the parser writes for with-open, which binds anything an
import/class can produce. A port or connection its scope owns is
released through the owner handle, so the registration does not stay on
the scope’s list. Anything else disposable is disposed. A standard port
is flushed and left open.
Not meant to be called directly.
See also: release!, own-disposable
ticks->duration
function ↑ Functions
(: ticks->duration (-> long Duration))
(ticks->duration t)
The duration of a number of 100 ns ticks.
t- Ticks, as a .NET TimeSpan counts them.
- returns
- The duration.
- raises
System.OverflowException - When t is long's minimum, the one tick count with no negation.
See also: duration-ticks
duration-ticks
function ↑ Functions
(: duration-ticks (-> Duration long))
(duration-ticks d)
A duration’s length in 100 ns ticks.
d- The duration.
- returns
- The ticks, a long.
See also: ticks->duration
milliseconds
function ↑ Functions
(: milliseconds (-> long Duration))
(milliseconds n)
A number of milliseconds, as a duration.
n- Milliseconds.
- returns
- The duration.
- raises
System.OverflowException - When n is outside ±29 227 years.
seconds
function ↑ Functions
(: seconds (-> long Duration))
(seconds n)
A number of seconds, as a duration.
n- Seconds.
- returns
- The duration.
- raises
System.OverflowException - When n is outside ±29 227 years.
(with-deadline (seconds 5) (fetch url))
See also: milliseconds, minutes, hours, with-deadline, timeout
minutes
function ↑ Functions
(: minutes (-> long Duration))
(minutes n)
A number of minutes, as a duration.
n- Minutes.
- returns
- The duration.
- raises
System.OverflowException - When n is outside ±29 227 years.
See also: milliseconds, seconds, hours
hours
function ↑ Functions
(: hours (-> long Duration))
(hours n)
A number of hours, as a duration.
n- Hours.
- returns
- The duration.
- raises
System.OverflowException - When n is outside ±29 227 years.
See also: milliseconds, seconds, minutes
duration->timer-ms
function ↑ Functions
(: duration->timer-ms (-> Duration long))
(duration->timer-ms d)
The milliseconds a timer waits for a duration.
d- The duration.
- returns
- The milliseconds, a long: 0 for zero or less, and a part of a millisecond counted as a whole one.
What with-deadline and with-shield give the scope openers.
A part of a millisecond counts as a whole one, so a positive duration
does not become zero, which a timer takes as a time already passed.
See also: timeout, with-deadline, Duration
make-clock
function ↑ Functions
(: make-clock (-> (#:monotonic-ms (-> long)) (#:monotonic-ns (Option (-> long))) (#:utc-ticks (-> long)) (#:zone (-> System.TimeZoneInfo)) (#:advance (Option (-> long void))) Clock))
(make-clock #:monotonic-ms clock-ms #:monotonic-ns None #:utc-ticks system-utc-ticks
#:zone system-zone #:advance None)
A clock, with each part not given taken from the system’s.
#:monotonic-ms- Reads the monotonic milliseconds.
#:monotonic-ns- Reads the monotonic nanoseconds, or
None: then they are the milliseconds times a million. #:utc-ticks- Reads the wall clock in .NET ticks, UTC.
#:zone- Function returning the local time zone.
#:advance- Moves the clock on by a number of ticks, or
None. - returns
- The clock.
(parameterize ((current-clock (make-clock #:monotonic-ms (fun () 0L))))
(time-the-thing)) ; every stopwatch inside reads 0
(std datetime) has fixed-clock, manual-clock and
clock-in for the clocks a test wants.
A clock given only #:monotonic-ms reads its nanoseconds from those
milliseconds, so a fake clock gives the same exact elapsed time in both
units. Any other clock given no #:monotonic-ns, such as one given
only #:utc-ticks, therefore has nanoseconds of millisecond
resolution. system-clock has the timer’s own.
See also: Clock, system-clock, current-clock
monotonic-ms
function ↑ Functions
(: monotonic-ms (-> (#:clock Clock) long))
(monotonic-ms #:clock (parameter-ref current-clock))
The clock’s monotonic reading, in milliseconds.
#:clock- The clock to read.
- returns
- Milliseconds from an unspecified start. Only differences mean anything.
For measuring how long something took. Not the wall-clock time, which is
(std datetime)’s now. For what takes less than a
millisecond, use monotonic-ns.
See also: current-clock, Clock
monotonic-ns
function ↑ Functions
(: monotonic-ns (-> (#:clock Clock) long))
(monotonic-ns #:clock (parameter-ref current-clock))
The clock’s monotonic reading, in nanoseconds.
#:clock- The clock to read.
- returns
- Nanoseconds from an unspecified start. Only differences mean anything.
The same clock as monotonic-ms, at the resolution the clock has: on
system-clock, the resolution of System.Diagnostics.Stopwatch.
(std stopwatch) measures with it.
See also: monotonic-ms, current-clock, Clock
SSym
function ↑ Functions
(: SSym (-> Symbol Syntax))
An identifier, as a Syntax.
s- Its name.
- returns
- The identifier. Built in a transformer, it is renamed by hygiene.
SSym and SDatum carry the same payload and mean opposite
things to hygiene: an SSym a transformer constructs is renamed
apart from the call site, an SDatum never is. An identifier made
from a string, (SSym (string->symbol ...)), is renamed like any
other the transformer builds; inject makes one that binds at the
call site.
See also: SDatum, syntax-ident=?
SDatum
function ↑ Functions
(: SDatum (-> Symbol Syntax))
A quoted symbol written as data, ‘foo, as a Syntax.
s- The symbol.
- returns
- The datum. Never renamed by hygiene: it is a value, not a reference to a binding.
See also: SSym
SInt
function ↑ Functions
(: SInt (-> string Syntax))
A numeric literal, as a Syntax.
text- The literal as written, such as
"1"or"1.5". - returns
- The literal.
Text rather than a number, since the same case carries 1 and
1.5 and which one it is has not been decided when a macro runs.
SStr
function ↑ Functions
(: SStr (-> string Syntax))
A string literal, as a Syntax.
text- The string.
- returns
- The literal.
SChar
function ↑ Functions
(: SChar (-> char Syntax))
A character literal, as a Syntax.
c- The character.
- returns
- The literal.
SKey
function ↑ Functions
(: SKey (-> Keyword Syntax))
A keyword such as #:when, as a Syntax.
k- The keyword.
- returns
- The keyword as syntax.
SList
function ↑ Functions
(: SList (-> (List Syntax) Syntax))
A parenthesized form, as a Syntax.
items- What is inside it, in order.
- returns
- The form.
(match form
((SList (Cons _ (Cons only Nil))) ...) ; exactly one argument
((SList (Cons _ rest)) ...)) ; any number
It holds a real (List Syntax), so map, folds and the
trailing rest pattern work on a macro’s input.
SPunct
function ↑ Functions
(: SPunct (-> string Syntax))
A punctuation token that survives reading, as a Syntax.
text- Its spelling:
,,@:.or.... - returns
- The token.
These are not identifiers and not data, but they reach a macro: a comma
is an optional argument separator, (: name type) is a signature
and ... is a rest pattern. Carrying the spelling is what lets an
input form be handed back exactly as it was read.
syntax-error
function ↑ Functions
(: syntax-error (-> Syntax string Syntax))
Rejects a macro’s input with a message; never returns.
form- The syntax the message is about. It is quoted in the message.
msg- What is wrong, and preferably how the macro is written.
- returns
- Nothing: it throws. Typed as Syntax so it can appear in expression positions returning Syntax.
- raises
System.InvalidOperationException - Always, with the message followed by the form.
(syntax-match form
((_ x) #'(let ((v ,x)) (+ v v)))
(bad (syntax-error bad "twice takes one argument.")))
How a transformer rejects its input. The expander catches the exception and reports the message against the macro’s call site.
See also: syntax-at, syntax->string
syntax-at
function ↑ Functions
(: syntax-at (-> Syntax Syntax Syntax))
A form carrying the source position of another piece of syntax.
form- The form, usually one a transformer built.
source- A piece of the input, whose position is copied.
- returns
formwithsource's position, orformunchanged whensourcehas none.
Everything a transformer builds is reported at the macro’s call site.
With this, an error in code built from one argument points at that
argument instead: get and set use it to report an error at
the step that caused it. A position can only be copied from input, never
made up.
See also: syntax-line, syntax-file
syntax-file
function ↑ Functions
(: syntax-file (-> Syntax string))
The file a piece of syntax was read from.
s- The syntax.
- returns
- The file's path, or
"<unknown>"for syntax with no position, such as what a transformer has just built.
See also: syntax-line, syntax-at
syntax-line
function ↑ Functions
(: syntax-line (-> Syntax int))
The line a piece of syntax starts on.
s- The syntax.
- returns
- The line, or 0 for syntax with no position, such as what a transformer has just built.
See also: syntax-file, syntax-at
syntax-ident=?
function ↑ Functions
(: syntax-ident=? (-> Syntax Syntax bool))
Whether two pieces of syntax are the same identifier.
a- The first.
b- The second.
- returns
- #t when both are identifiers or quoted symbols with the same base name; #f otherwise, including when either is not one.
The value-level compare: the test a transformer gets as its third
parameter, available to any code. A syntax-match pattern’s
'name compiles to a call to it.
Names are compared with hygiene marks stripped, so an identifier built by
one macro and handed to another is still recognised. A quoted symbol
counts, so 'else matches an input that wrote else or
'else. It is not denotational equality: a name the caller has
rebound locally still compares equal.
syntax->string
function ↑ Functions
(: syntax->string (-> Syntax string))
Renders a piece of syntax back to something that reads as source.
s- The syntax.
- returns
- Its source text: a list in parentheses with its items separated by spaces, a quoted symbol with its quote, a string in quotes with its quotes and backslashes escaped.
What a macro’s error message wants to quote.
See also: syntax-error
syntax-resolved
function ↑ Functions
(: syntax-resolved (-> Symbol Syntax))
An identifier that hygiene leaves alone and that resolves where the template was written.
s- Its name.
- returns
- An identifier with the resolved origin.
What the str and displayed of a #"..." written inside a
#' template desugar to. The expander lowers it back to a
reference no binding at the call site can capture. It is what the
compiler writes for a template, not meant to be called directly.
See also: SSym
syntax-splice
function ↑ Functions
(: syntax-splice (-> (List Syntax) (List Syntax) (List Syntax)))
Two lists of syntax, one after the other: what a splice in a template compiles to.
a- The items before.
b- The items after.
- returns
- The items of a followed by those of b.
The append behind ,@ in a #' template. It is what the
compiler writes, not meant to be called directly; it works without the
prelude’s own list functions, which a module compiled without the prelude
does not have.
Values
unit
value ↑ Values
(: unit void)
The single value of type Unit.
Used when an expression or function body must evaluate to Unit
without performing meaningful work, such as in Discard’s blanket
implementation. Equivalent to (begin). Not to be confused with
(Tuple), which is the empty tuple.
See also: ignore
None
value ↑ Values
(: None (Option %a))
The Option that holds nothing.
(match (map-try-ref m k)
((Some v) v)
(None 0))
See also: Some, none?, option-ref-or
Nil
value ↑ Values
(: Nil (List %a))
The empty list.
(match xs
(Nil "empty")
((Cons _ _) "not empty"))
The other case of a list, with Cons. It is a value, not a
function: written Nil, not (Nil).
See also: Cons, list-empty, list-empty?
op/fs-info
value ↑ Values
(: op/fs-info (Param (-> Path (Option FsInfo))))
The parameter holding the handler fs-info calls.
with-handler binds it when it installs a handler for
fs-info, and (handler-of fs-info) reads it. Under a prefix
or a rename, where with-handler cannot derive this name from the
operation’s, parameterize it directly. Cold: it takes none of the
dynamic environment’s cheap parameter ids.
See also: fs-info, fs-info/raw
op/fs-list
value ↑ Values
(: op/fs-list (Param (-> Path (Result Exception (Vec FsEntry)))))
The parameter holding the handler fs-list calls.
with-handler binds it when it installs a handler for
fs-list, and (handler-of fs-list) reads it. Cold.
See also: fs-list, fs-list/raw
op/fs-create-directory
value ↑ Values
(: op/fs-create-directory (Param (-> Path (Result Exception Unit))))
The parameter holding the handler fs-create-directory calls.
with-handler binds it when it installs a handler for
fs-create-directory. Cold.
See also: fs-create-directory, fs-create-directory/raw
op/fs-delete-file
value ↑ Values
(: op/fs-delete-file (Param (-> Path (Result Exception Unit))))
The parameter holding the handler fs-delete-file calls.
with-handler binds it when it installs a handler for
fs-delete-file. Cold.
See also: fs-delete-file, fs-delete-file/raw
op/fs-delete-directory
value ↑ Values
(: op/fs-delete-directory (Param (-> Path (Result Exception Unit))))
The parameter holding the handler fs-delete-directory calls.
with-handler binds it when it installs a handler for
fs-delete-directory. Cold.
See also: fs-delete-directory, fs-delete-directory/raw
op/fs-move
value ↑ Values
(: op/fs-move (Param (-> Path Path MoveMode (Result Exception Unit))))
The parameter holding the handler fs-move calls.
with-handler binds it when it installs a handler for
fs-move. Cold.
See also: fs-move, fs-move/raw
op/getenv
value ↑ Values
(: op/getenv (Param (-> string (Option string))))
The parameter holding the handler getenv calls.
with-handler binds it when it installs a handler for
getenv, and (handler-of getenv) reads it. Under a prefix or
a rename, parameterize it directly. Cold: it takes none of the
dynamic environment’s cheap parameter ids.
See also: getenv
current-input-port
value ↑ Values
(: current-input-port (Param Bjolang.Runtime.BjoInputPort))
The port standard input is read from.
(read-line (parameter-ref current-input-port))
A (Param InputPort), read with parameter-ref and rebound
with parameterize. There is no read without a port: standard
input is read as any other port is.
Its default is standard input, buffered once for the whole program, so
port-eof? on it usually costs no system call. Closing it does
nothing.
It is a port over standard input’s raw bytes, as every port is: its text reads decode UTF-8 whatever the console’s encoding, and its byte reads work on piped binary input. On a terminal the terminal edits and echoes each line, and Ctrl-D at the start of a line is end of input.
See also: current-output-port, read-line, port-eof?
current-output-port
value ↑ Values
(: current-output-port (Param Bjolang.Runtime.BjoOutputPort))
The port display, displayln and newline write to.
(def out (open-output-string))
(parameterize ((current-output-port out))
(display "captured"))
(get-output-string out) ; "captured"
A (Param OutputPort). Its default is standard output, which the
runtime does not buffer. Binding it with parameterize redirects
display, displayln, newline, print and
println.
close-output-port on standard output flushes it and does nothing
more.
See also: current-error-port, display, write-string
current-error-port
value ↑ Values
(: current-error-port (Param Bjolang.Runtime.BjoOutputPort))
The port for errors and diagnostics, standard error by default.
A (Param OutputPort). The default handlers of warn and
log write a line to it. close-output-port on standard error
flushes it and does nothing more.
See also: current-output-port, warn, log
op/open-read-stream
value ↑ Values
(: op/open-read-stream (Param (-> Path (Result Exception ClrStream))))
The parameter holding the open-read-stream operation’s handler.
What (with-handler ((open-read-stream h)) ...) binds. It is cold:
files are not opened in a loop, so it spends none of the cheap parameter
ids. Bind it with parameterize directly when the operation was
imported under another name, so that with-handler cannot find
the cell by spelling.
See also: open-read-stream, open-read-stream/raw
op/open-write-stream
value ↑ Values
(: op/open-write-stream (Param (-> Path WriteMode (Result Exception ClrStream))))
The parameter holding the open-write-stream operation’s handler.
What (with-handler ((open-write-stream h)) ...) binds. It is
cold, like the other operations of the FS effect.
See also: open-write-stream, open-write-stream/raw
op/warn
value ↑ Values
(: op/warn (Param (-> string void)))
The parameter holding the warn operation’s handler.
What (with-handler ((warn h)) ...) binds. Bind it with
parameterize directly when warn was imported under another
name, so that with-handler cannot find the cell by spelling.
See also: warn
op/log
value ↑ Values
(: op/log (Param (-> string void)))
The parameter holding the log operation’s handler.
(parameterize ((p:op/log collect)) ...)
What (with-handler ((log h)) ...) binds. Bind it with
parameterize directly when log was imported under a prefix
or another name, so that with-handler cannot find the cell by
spelling.
See also: log
current-cancel
value ↑ Values
(: current-cancel (Param CancelToken))
The ambient cancellation token, which every sync watches.
A (Param CancelToken). A scope installs its token here for its
body, and a spawned fiber starts with the environment it was spawned in,
so the whole subtree sees the same token without one being passed
anywhere.
Outside every scope it is a token that never fires. Inside a
with-shield it is the shield’s own, which a cancellation outside
the shield does not fire.
A bare (parameterize ((current-cancel t)) ...) binds the token
without changing which scope a spawn goes into.
See also: sync, cancelled?, with-cancel, current-scope
Deadline
value ↑ Values
(: Deadline CancelReason)
A cancellation reason: a time limit ran out.
What the timer of with-deadline or with-shield fires its
scope’s token with.
See also: with-deadline, with-shield, Requested
Scope-Ended
value ↑ Values
(: Scope-Ended CancelReason)
A cancellation reason: the scope owning the token has finished.
A scope fires its token with this once every child it waits for has landed, unless the token fired earlier, so a daemon or a fiber handed the token stops rather than outliving the scope.
See also: with-cancel, Requested
system-clock
value ↑ Values
(: system-clock Clock)
The machine’s clock, in the machine’s zone.
See also: current-clock, make-clock
current-clock
value ↑ Values
(: current-clock (Param Clock))
The clock monotonic-ms and (std datetime) read.
A cold (Param Clock), starting as system-clock. Binding it
fixes both monotonic-ms and (std datetime)’s now and
today.
See also: system-clock, make-clock, monotonic-ms
currently-in-repl
value ↑ Values
(: currently-in-repl (Param bool))
Whether the code is running in a REPL.
A cold (Param bool): #t while the REPL runs an entry, #f in a built
program. panic! reads it, and at a prompt raises instead of ending
the process.
See also: panic!
Macros
select
macro ↑ Macros
(select branch ...)
Syncs on the events of its branches, then runs the body of the branch whose event committed.
branch ...(event pattern body ...),(#:timeout duration body ...)or(#:else body ...).
(select
((chan-recv requests) r (handle r))
((chan-recv quit) _ 'stopped)
(#:timeout (seconds 5) 'idle))
The value of the form is the value of the body that ran.
In (event pattern body ...), event is any event. When it commits,
its value is matched against pattern and body runs.
(#:timeout duration body ...) is a branch on
(timeout duration). (#:else body ...) runs when no other
branch can commit at once, and the form then does not wait. It must be
the last branch.
Each event has its own value type. The bodies have one type, which is the type of the form. A pattern must match every value of its event: a pattern that can fail is a compile error.
The events are offered in the order written, as by choose: when
several can commit at once, the first one wins. A branch that loses runs
no body, and the nack of a with-nack in it fires.
The bodies run after the sync, in the code that the form is in. In a
bjoroutine a body can suspend: it can sync, and call a bjoroutine. In a
defun the form parks the thread, as sync/blocking does.
It expands to a choose of wraps and a match. With
two to four branches the compiler emits that choose as one event,
which the thread keeps, and whose sink the fiber’s pooled sync state
keeps: a warm sync allocates nothing. A choose of wraps
written by hand directly in a sync gets the same.
with-scope
macro ↑ Macros
(with-scope body ...)
Runs body in a scope that waits for its fibers and releases what it owns.
body ...- What to run. Its last value is the form's.
(with-scope
(match (open-input-file "notes.txt")
((Ok p) (read-all p)) ; closed when the scope returns
((Err e) "")))
A with-cancel whose cancel thunk nothing in the body can reach: the
plain form, and the one to put around resources. It waits for every fiber
spawn, bjo or spawn-thunk started in it, then
releases what was owned in it, newest first.
In a bjoroutine the wait suspends. In ordinary code, a defun or a
(fun ...), it parks the thread, and the blocking lint reports it
when a bjoroutine reaches it.
See also: with-cancel, own!, in-scope
with-cancel
macro ↑ Macros
(with-cancel (cancel) body ...)
Runs body in a scope that owns the fibers it starts, with a thunk to cancel them.
cancel- The name the cancel thunk is bound to. It takes a reason.
body ...- What to run. Its last value is the form's.
(with-cancel (cancel)
(spawn (worker jobs results))
(def res (sync (chan-recv results)))
(cancel (Requested "got it"))
res)
Opens a scope whose token is linked to the ambient one, installs it as the
current scope and current-cancel for the body, and closes it on the
way out. The binding is restored however the body is left.
The order on the way out. When the body leaves with an
exception, the token fires with (Failed e) first; so it does when
a child had already failed. Then the scope waits for every child, fires
the token with Scope-Ended if it has not fired, and runs its
releases newest first. Only then does it report. A scope whose children
never end, and which never calls cancel, hangs rather than
returning.
A child that fails does not interrupt the body: the token is
fired with (Failed e) once the body has ended, as above, or at once
if the child fails while the scope is already waiting. Its failure is
raised when the scope returns. Several failures, a release that threw
among them, are raised together as one System.AggregateException,
the body’s first. A child that stopped because it was cancelled has not
failed. A bjo child’s failure is its promise’s, and the scope does
not raise it again.
In a bjoroutine the wait suspends. In ordinary code it parks the thread,
as with-scope’s does.
See also: with-scope, with-deadline, with-shield, Requested, current-cancel
with-deadline
macro ↑ Macros
(with-deadline d body ...)
Runs body in a scope that is cancelled with Deadline after a length of time.
d- A Duration. Zero or less has passed already: the scope is cancelled at once. For no deadline, write with-scope.
body ...- What to run. Its last value is the form's.
(with-deadline (seconds 5)
(spawn (fetch "a"))
(spawn (fetch "b"))) ; returns once both have landed or been cancelled
with-cancel with a timer the scope owns. When it fires, the token
fires with Deadline, and every sync in the scope that has to
wait raises Cancelled. The body has no cancel thunk.
Running out of time is not itself a failure. A child stopped by the deadline has not failed, so the form above returns normally either way; it raises only when the body itself was stopped, or a child failed. A caller that needs to know reads the reason off the scope’s token.
Where the others waited. When the deadline stops the body, the
message of the Cancelled that it raises tells where each other
fiber that the deadline stopped was waiting, with the fibers of nested
scopes, counted by place:
When the deadline passed, 3 other fibers were waiting:
3 fibers at app.bjo:14 (ignore (sync (chan-recv jobs)))
The text is made from the stacks of the cancellations when the message
is read, so it costs nothing before that. For every fiber of the
program, at any time, see fiber-trace.
See also: with-cancel, seconds, timeout, Deadline
with-shield
macro ↑ Macros
(with-shield body ...)
(with-shield #:within d body ...)
Runs body in a scope that a cancellation outside it does not reach.
d- The shield's own deadline, a Duration above zero. Thirty seconds when it is not given.
body ...- What to run. Its last value is the form's.
(with-shield #:within (seconds 5)
(spawn (flush-buffer a))
(spawn (flush-buffer b)))
How cleanup runs after a cancellation. Once a scope has been cancelled
every sync in it raises, including those in the code trying to
tidy up. Inside a shield the ambient token is a fresh one, not linked to
the parent’s, so a sync works again, and
current-cancel agrees with it.
The deadline is not optional: a shield nothing outside can reach and that
never times out would make the program impossible to stop. So a duration
of zero or less raises System.ArgumentOutOfRangeException. It is a
scope, so it waits for its own children.
See also: with-cancel, current-cancel
in-scope
macro ↑ Macros
(in-scope s body ...)
Runs body with a given scope as the ambient one.
s- The scope, from
current-scope. body ...- What to run. Its last value is the form's.
(def home (current-scope))
(on-event (fun (e) (in-scope home (handle e))))
The way to own something in a scope other than the innermost one, and the way back in from a .NET callback, which arrives on a thread with no ambient scope at all.
It installs a scope; it does not open or close one, and it does not suspend. Whoever opened s is still the one that waits for it.
See also: current-scope, own!, with-scope
own-disposable
macro ↑ Macros
(own-disposable x)
Registers an IDisposable’s Dispose method on the ambient scope, returning the resource.
x- An expression evaluating to an object with a
.Disposemethod.
(def reader (own-disposable (StreamReader. path)))
(own! (fun () (.Dispose x))), returning x. A form so that
.Dispose resolves at the call site, as with-open resolves
it. with-open is for a resource whose lifetime is one block; this
is for one whose lifetime is the scope’s.
See also: own!, with-scope
scope-form
macro ↑ Macros
(scope-form opener (cancel) first body ...)
The shared expansion of with-scope, with-cancel, with-deadline and with-shield.
opener- The call that makes the scope:
scope-open!orshield-open!. cancel- The name the cancel thunk is bound to.
first- The body's first form.
body ...- The rest of the body.
Opens the scope, installs it with scope-push!, binds the thunk from
scope-canceller, runs the body, and closes the scope with
scope-close! in a bjoroutine and scope-close!/blocking in
ordinary code, telling it about the body’s exception if there was one, which is then raised again unless the close raised first. dyn-restore! puts the old
environment back however the form is left.
Not meant to be written by hand: use one of the four forms.
See also: with-scope, with-cancel, with-deadline, with-shield