Compare commits
38 commits
| Author | SHA256 | Date | |
|---|---|---|---|
| 5e07283404 | |||
| 6634469ae8 | |||
| 7d1cc99efe | |||
| dc629fbd3e | |||
| 902ff84662 | |||
| f07cd79e3e | |||
| 1a2a43bf5a | |||
| 93025b7b35 | |||
| 6ee8ca62b9 | |||
| d16bf477a1 | |||
| 2334da2516 | |||
| d05f4c91dd | |||
| 623b68513c | |||
| 4d29d7b7b6 | |||
| 0e6ff36076 | |||
| 1e7c54fcc6 | |||
| 3173c7176f | |||
| c791af1593 | |||
| 2a4e3b3fcf | |||
| ae58a1e004 | |||
| 1a407720a9 | |||
| 684745d6c0 | |||
| 5a9f65accf | |||
| 25720e4fb2 | |||
| e448ee0d93 | |||
| 481538a1cb | |||
| bd71102c19 | |||
| 6d9c9bf8a0 | |||
| 8729cb3ef7 | |||
| cefa2313ad | |||
| 3f8c13cc2f | |||
| 84000bf384 | |||
| 4f8da92dc2 | |||
| 5bc42069cd | |||
| 21fa7af6dc | |||
| aaf92b38c1 | |||
| 21d0c9de06 | |||
| 15bfc18167 |
26 changed files with 1542 additions and 206 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1 +1,2 @@
|
|||
_cache/
|
||||
.netcoredbg_hist
|
||||
|
|
|
|||
|
|
@ -24,21 +24,20 @@ git pull
|
|||
|
||||
@subsection{Your first bjolang program}
|
||||
|
||||
Bjolang compiles to c#. Many of the design decisions behind bjolang stems from this limitation. The first one you will encounter is that a program needs a main function. like the one in c#, that returns an int. If execution ended correctly it should return 0 if the program executed successfully.
|
||||
Bjolang compiles to c#. Many of the design decisions behind bjolang stems from this limitation. The first one you will encounter is that a program needs a main function, like the one in c#. An int it returns is the program's exit code, 0 when it ran correctly; a main that returns anything else exits with 0.
|
||||
|
||||
@codeblock[#:lang "bjolang"]{
|
||||
(: print-hello (-> string unit))
|
||||
(: print-hello (-> string void))
|
||||
(defun (print-hello name)
|
||||
(println (str "Hello, " name "!")))
|
||||
|
||||
(defun (main args)
|
||||
(print-hello "User")
|
||||
0)
|
||||
(print-hello "User"))
|
||||
}
|
||||
|
||||
This can then be run using @code{bjo run filename}, and it should print @code{Hello, User!}.
|
||||
|
||||
What you can see here is that defun is the form for defining a function. main is special, it needs no type declaration. print-hello is a regular function, and thus has to declare its type. Everything at toplevel needs to do that. The form is (: name type). A function type is declared as (-> ArgType ... Return-Type). print-hello takes a string argument and returns unit. unit is the name for nothing.
|
||||
What you can see here is that defun is the form for defining a function. main is special, it needs no type declaration. print-hello is a regular function, and thus has to declare its type. Everything at toplevel needs to do that. The form is (: name type). A function type is declared as (-> ArgType ... Return-Type). print-hello takes a string argument and returns void. void is the name for nothing: the unit type, whose one value is what println gives back.
|
||||
|
||||
@subsection{Declaring types}
|
||||
For most of your bjolang code, you will only declare types in the top level. Types within functions are inferred, so declaring types there is almost never necessary. A value type is declared just like a function, but without the function type declaration:
|
||||
|
|
@ -62,7 +61,7 @@ You can also declare your own types. Either aliases of other types, records of y
|
|||
This can then be destructed using pattern matching.
|
||||
|
||||
@codeblock[#:lang "bjolang"]{
|
||||
(: print-user (-> User unit))
|
||||
(: print-user (-> User void))
|
||||
(defun (print-user u)
|
||||
(match u
|
||||
;; Subpatterns: here we match name, age, the Card rank
|
||||
|
|
@ -105,9 +104,11 @@ Then there are some special cases, like string interpolation:
|
|||
(a-string "hej"))
|
||||
(println $"This is interpolated: ${an-int} ${a-string}")
|
||||
;; Which is literally the same as:
|
||||
(println (str "This is interpolated: " (->str an-int) " " (->str a-string))))
|
||||
(println (str "This is interpolated: " (displayed an-int) " " (displayed a-string))))
|
||||
}
|
||||
|
||||
Each hole goes through @code{displayed}, so a string hole gives its text without quotes. See @em{Converting to and from strings} below.
|
||||
|
||||
@subsubsection{Function types}
|
||||
|
||||
A function takes any number of arguments and produces a value. The signature of a function in bjolang is denoted using the arrow @code{->}:
|
||||
|
|
@ -119,14 +120,14 @@ A function takes any number of arguments and produces a value. The signature of
|
|||
;; the last expression in the body is the return value
|
||||
(* x 2))
|
||||
|
||||
(:print-n-times (-> string int unit))
|
||||
(: print-n-times (-> string int void))
|
||||
(defun (print-n-times what n)
|
||||
(loop (:for i (up-from 0 #:to n))
|
||||
(println what)))
|
||||
(:do (println what))))
|
||||
|
||||
;; call twice takes a function take takes an argument
|
||||
;; of type %a and returns unit.
|
||||
(: call-twice (-> (-> %a unit) %a unit))
|
||||
;; of type %a and returns void.
|
||||
(: call-twice (-> (-> %a void) %a void))
|
||||
(defun (call-twice f val)
|
||||
(f val)
|
||||
(f val))
|
||||
|
|
@ -163,11 +164,40 @@ Everything at the toplevel needs a signature, even values. In a function body, n
|
|||
|
||||
The example above is of course facile, but it matters more for generic functions with inlined traits. They are pinned to the first use, and any subsequent usage will raise an error. More on this in the trait section.
|
||||
|
||||
@subsubsection{Typed holes}
|
||||
|
||||
When you don't know what to write somewhere, write @code{_} there. That is a typed hole (not to be confused with the holes of string interpolation). A program with a typed hole does not compile. Instead the compiler tells you what type is wanted at that spot, and which bindings in scope have that type:
|
||||
|
||||
@codeblock[#:lang "bjolang"]{
|
||||
(: lengths (-> (Vec string) (Vec int)))
|
||||
(defun (lengths names)
|
||||
(vec-map _ names))
|
||||
}
|
||||
|
||||
@codeblock[#:lang "text"]|{
|
||||
Hole at lengths.bjo:3:12: '_' stands for a value of type (-?-> string int).
|
||||
Bindings in scope that fit: string-count, unhashable, count, eq-hash, length, structural-hash, and 2 more.
|
||||
}|
|
||||
|
||||
@code{-?->} is a function that may or may not suspend, which is what @code{vec-map} accepts. More on that under Concurrency.
|
||||
|
||||
The bindings closest to the hole are listed first: locals, then your own module's, then imported ones. A binding with a where clause is only listed if the clause holds. A name that starts with an underscore, like @code{_total}, is a hole too as long as nothing binds it, which is handy when you have several. If nothing around the hole decides its type, you get a @code{?a} and what it has to be able to do, like @code{(Displayed ?a)}. In the REPL, @code{(: _ string)} is a quick way to ask what in scope is a string.
|
||||
|
||||
While a hole's type is still open, the other errors in the same definition are held back, since they are often caused by the hole. Once you fill it in, they show up.
|
||||
|
||||
In an editor that uses the Bjolang language server, a hole has code actions: fill it with one of the bindings that fit, with a constructor of its type such as @code{(Circle _)}, or, where a function is wanted, with @code{(fun (x y) _)}. What you fill in can have holes of its own, so you can build an expression a step at a time and let the compiler tell you what each part has to be.
|
||||
|
||||
@subsubsection{Unused definitions}
|
||||
|
||||
The compiler warns about definitions nothing uses: a top-level @code{def} or @code{defun} that the module doesn't export and nothing in it reads, and a local binding (a @code{let}, a @code{def} in a body, a loop variable) that nothing in its scope reads. Dead code piles up quietly in a large program, and this keeps it from doing so.
|
||||
|
||||
If you keep something on purpose, start its name with an underscore: @code{(def _registered (register!))}, or @code{(:for _ (range 0 n))} for a loop that just repeats. Parameters and pattern variables are not checked.
|
||||
|
||||
@subsubsection{Naming conventions}
|
||||
|
||||
Bjolang follows scheme's naming conventiens. Predicates end with @code{?}. Mutating functions end with @code{!}. Conversions are written using @code{->}.
|
||||
|
||||
While the base types are lowercase (which is a design mishap), types should be capitalized. Record and struct fields are lower case.
|
||||
While the base types are lowercase (which is a design mishap), types should be capitalised. Record and struct fields are lower case.
|
||||
|
||||
@subsection{Functions}
|
||||
|
||||
|
|
@ -355,6 +385,63 @@ A type alias is a different name for a type that already exists. It is declared
|
|||
(type (: Stringalias string))
|
||||
}
|
||||
|
||||
@subsubsection{Newtypes}
|
||||
|
||||
A newtype is the opposite of an alias: a type of its own, which the compiler will not mix up with the type it wraps, but which is that type when the program runs, so it costs nothing.
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(type (: UserId (Newtype int)))
|
||||
(type (: OrderId (Newtype int)))
|
||||
|
||||
(def u (UserId 7)) ;; built by its name
|
||||
(def (UserId n) u) ;; taken apart by a pattern: n is 7
|
||||
|
||||
(: (-> UserId string))
|
||||
(defun (lookup-user id) ...)
|
||||
|
||||
(lookup-user (OrderId 7)) ;; a compile error: an OrderId is not a UserId
|
||||
}|
|
||||
|
||||
A newtype does not get the traits of the type it wraps: @code{(+ u u)} is an error, though @code{(+ 7 7)} is not. It gets those you give it, as the section on traits shows.
|
||||
|
||||
A newtype can have a type parameter that its value does not use. Such a parameter is called a @em{phantom}: it is only there to tell values apart. Instead of one newtype for each kind of id, there can be one @code{Id} that says what it is an id of. The tags are types with no values, written as unions with no cases:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(type (: User (Union))) ;; tags: types with no values
|
||||
(type (: Order (Union)))
|
||||
(type (: (Id %a) (Newtype int))) ;; %a is in no field
|
||||
|
||||
(: lookup-user (-> (Id User) string))
|
||||
(defun (lookup-user id) ...)
|
||||
|
||||
(: id-number (-> (Id %a) int)) ;; for an id of any kind
|
||||
(defun (id-number id)
|
||||
(def (Id n) id)
|
||||
n)
|
||||
|
||||
(lookup-user (: (Id 7) (Id Order))) ;; a compile error: an (Id Order) is not an (Id User)
|
||||
}|
|
||||
|
||||
An @code{(Id User)} is still an @code{int} when the program runs. A function can be written once for every kind of id, as @code{id-number} is, and a trait can have an implementation for each tag, such as one for @code{(Id User)} and another for @code{(Id Order)}.
|
||||
|
||||
A tag can also record what has been checked about a value. Here only @code{validate} can make an @code{(Email Valid)}, so @code{send} never gets an address nobody checked:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(type (: Raw (Union)))
|
||||
(type (: Valid (Union)))
|
||||
(type (: (Email %s) #:opaque (Newtype string)))
|
||||
|
||||
(: validate (-> (Email Raw) (Option (Email Valid))))
|
||||
(defun (validate e)
|
||||
(def (Email s) e)
|
||||
(if (string-contains? s "@") (Some (Email s)) None))
|
||||
|
||||
(: send (-> (Email Valid) void))
|
||||
(defun (send e) ...)
|
||||
}|
|
||||
|
||||
@code{#:opaque}, described under exporting types in "Writing programs", is what keeps another module from building an @code{(Email Valid)} itself, with @code{(Email s)}.
|
||||
|
||||
@subsubsection{Records and structs}
|
||||
Records and structs are direct mappings to c# records and immutable structs. The constructor is the type name, together with parenthesised fields. As follows.
|
||||
|
||||
|
|
@ -433,12 +520,34 @@ Unions can be generic. The type variables go after the type name, just like for
|
|||
|
||||
You never have to write these two, since the prelude already has them under the names @code{(Option %a)}, with the cases @code{None} and @code{Some}, and @code{(Result %e %a)}, with the cases @code{Err} and @code{Ok}. They are ordinary unions, and they get a section of their own further down.
|
||||
|
||||
Two unions can each have a case of the same name, in one module or in two. Which one a use of the name means is decided by its type: the type wanted where it is written, the type of the value a @code{match} takes apart, or the number of values it is given, when only one of the cases takes that many.
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(type (: Light (Union Red Amber Green)))
|
||||
(type (: Colour (Union Red Blue (: Grey int))))
|
||||
|
||||
(: stop (-> Light))
|
||||
(defun (stop) Red) ;; a Light, because stop returns one
|
||||
|
||||
(: colour-name (-> Colour string))
|
||||
(defun (colour-name c)
|
||||
(match c
|
||||
(Red "red") ;; Colour's, because c is a Colour
|
||||
(Blue "blue")
|
||||
((Grey n) "grey")))
|
||||
|
||||
(list Red Amber) ;; Lights, because Amber is
|
||||
(println (: Red Colour)) ;; written out
|
||||
}|
|
||||
|
||||
When nothing in the definition says which union is meant, a case your module declares wins over an imported one, and an imported one over the standard library's. If that does not decide it either, as for two @code{Red}s of your own in @code{(println Red)}, the compiler asks you to write the type: @code{(: Red Light)}.
|
||||
|
||||
A few things to know about unions:
|
||||
|
||||
@read-list{
|
||||
- Case names share a namespace with everything else in the module, so two unions in the same module cannot both have a case called @code{Red}.
|
||||
- A case cannot have the name of a record or a newtype of the same module, because those are built by their names too.
|
||||
- A union case cannot have a @code{#:mutable} field.
|
||||
- @code{println} on a union value without a @code{->str} implementation prints the generated C# name, something like @code{Card { rank = Queen { }, suit = Hearts { } }}. Implement @code{->str} (see the traits section) for anything you intend to print.
|
||||
- @code{println} on a value of your own type prints it as you would build it, for example @code{(Card (rank Queen) (suit Hearts))} or @code{(Pip 7)}. The compiler writes this for each type you declare. To print a type another way, implement @code{Displayed} (see the traits section).
|
||||
}
|
||||
|
||||
@subsubsection{Types that refer to themselves and each other}
|
||||
|
|
@ -525,23 +634,31 @@ The rest of this chapter uses a card game as a running example, so here are its
|
|||
(: tricks int))))
|
||||
|
||||
;; How a card prints. Traits are explained later; for now it is enough
|
||||
;; to know that this is what println and #"...${...}" use.
|
||||
(impl (->str Suit)
|
||||
(defun (->str s)
|
||||
(match s (Clubs "♣") (Diamonds "♦") (Hearts "♥") (Spades "♠"))))
|
||||
;; to know that Displayed is what println and #"...${...}" use, and that
|
||||
;; display-into adds the text to the string builder b.
|
||||
(impl (Displayed Suit)
|
||||
(defun (display-into s b)
|
||||
(stringbuilder-add-string! b
|
||||
(match s (Clubs "♣") (Diamonds "♦") (Hearts "♥") (Spades "♠")))))
|
||||
|
||||
(impl (->str Rank)
|
||||
(defun (->str r)
|
||||
(match r
|
||||
((Pip n) (int->string n))
|
||||
(Jack "J") (Queen "Q") (King "K") (Ace "A"))))
|
||||
(impl (Displayed Rank)
|
||||
(defun (display-into r b)
|
||||
(stringbuilder-add-string! b
|
||||
(match r
|
||||
((Pip n) (int->string n))
|
||||
(Jack "J") (Queen "Q") (King "K") (Ace "A")))))
|
||||
|
||||
(impl (->str Card)
|
||||
(defun (->str c) #"${(record-ref c rank)}${(record-ref c suit)}"))
|
||||
(impl (Displayed Card)
|
||||
(defun (display-into c b)
|
||||
(display-into (record-ref c rank) b)
|
||||
(display-into (record-ref c suit) b)))
|
||||
|
||||
(println (Card (rank Queen) (suit Hearts))) ;; Q♥
|
||||
(written (Card (rank Queen) (suit Hearts))) ;; "(Card (rank Queen) (suit Hearts))"
|
||||
}|
|
||||
|
||||
Without the three implementations, @code{println} prints the card as it is written: @code{(Card (rank Queen) (suit Hearts))}.
|
||||
|
||||
@code{Card} is a struct because it is two small values and is copied around a lot. @code{Player} is a record because it holds a whole hand. That is the usual rule of thumb: a struct for something small that behaves like a value, a record for everything else. A struct also cannot contain itself and cannot have mutable fields.
|
||||
|
||||
Records are updated by copying, with @code{record-set}:
|
||||
|
|
@ -862,6 +979,8 @@ The counterexample is a real value, and for nested patterns it tells you exactly
|
|||
Pattern Error at cards.bjo:8: this match does not cover every value. (Card (rank Ace) (suit Clubs)) reaches no clause.
|
||||
}|
|
||||
|
||||
In an editor that uses the Bjolang language server, an incomplete match has a code action that adds the clauses it lacks, nested cases spelled out, each with a typed hole as its body: @code{((Square _) _)}.
|
||||
|
||||
A clause that can never run, because the clauses above it already match everything it would, is also an error:
|
||||
|
||||
@codeblock[#:lang "text"]|{
|
||||
|
|
@ -1213,6 +1332,18 @@ An @code{Array} is a plain .NET array: mutable, fixed in length, and exactly wha
|
|||
|
||||
Every evaluation of an array literal makes a fresh array, so a function that returns @code{#[0 0]} returns a new one each time.
|
||||
|
||||
To work on part of an array without copying it, make a span: @code{(Span %a)} is a writable view (.NET's @code{Span<T>}) and @code{(RoSpan %a)} is a read-only view (@code{ReadOnlySpan<T>}).
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(def s (array->span a #:from 1 #:to 3))
|
||||
(span-length s) ;; 2
|
||||
(span-ref s 0) ;; 2
|
||||
(span-set! s 0 99) ;; writes into a: a is now #[42 99 3]
|
||||
(span->array s) ;; #[99 3], a fresh copy
|
||||
}|
|
||||
|
||||
A span is valid only while the call that made it runs, so it can be a local variable, a function argument or a return value, and the compiler refuses it anywhere it could outlive the call (such as inside another collection or across a yield point). The section on .NET interop in Part 2 covers the full rules and how spans work with .NET methods. It also covers @code{span->} and @code{ro-span->}, which show a span of numbers as numbers of another type (longs as bytes, for example) without copying.
|
||||
|
||||
@subsubsection{Maps}
|
||||
|
||||
@code{Map} is an immutable hash map. The @code{#map(...)} literal takes entries written as @code{(key value)}, @code{[key value]} or @code{(key . value)}.
|
||||
|
|
@ -1399,7 +1530,7 @@ There are three ways to repeat something in bjolang. A named @code{let} (or any
|
|||
|
||||
@subsubsection{loop}
|
||||
|
||||
A @code{loop} is a list of clauses that run in order, once per element. @code{(:for x coll)} walks anything that can be walked: lists, vecs, arrays, maps, strings, ranges and sequences. An accumulator collects a result, and @code{=> expr} says what the loop returns:
|
||||
A @code{loop} is a list of clauses that run in order, once per element. @code{(:for x coll)} walks anything that can be walked: lists, vecs, arrays, maps, strings, ranges, sequences, and streams, whose values come from work that suspends (Part 2, Concurrency). An accumulator collects a result, and @code{=> expr} says what the loop returns:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(loop (:for x (list 1 2 3 4 5 6))
|
||||
|
|
@ -1456,10 +1587,32 @@ An accumulator names a collector and what to feed it:
|
|||
| @code{(summing x)} | the sum of @code{x} |
|
||||
| @code{(counting x)} | how many rounds reached it |
|
||||
| @code{(folding init expr)} | starts at @code{init}; each round, @code{expr} is the new value |
|
||||
| @code{(finding x)} | @code{(Some x)} for the first round that reaches it, which ends the loop, or @code{None} |
|
||||
| @code{(someing e)} | the first @code{(Some v)} the @code{Option} @code{e} gives, which ends the loop, or @code{None} |
|
||||
| @code{(anding test)} | whether @code{test} holds in every round; the first that fails ends the loop |
|
||||
| @code{(oring test)} | whether @code{test} holds in some round; the first that holds ends the loop |
|
||||
| @code{(taking n x)} | a @code{List} of the first @code{n}; the @code{n}th ends the loop |
|
||||
| @code{(maximizing x)} | @code{(Some x)} of the greatest, by @code{Ord}, or @code{None} (and @code{minimizing}) |
|
||||
| @code{(maximizing-by k x)} | @code{(Some x)} of the greatest key @code{k}, or @code{None} (and @code{minimizing-by}) |
|
||||
| @code{(tallying x)} | a @code{Map} from each value to how many times it came |
|
||||
| @code{(grouping k x)} | a @code{Map} from each key @code{k} to the @code{List} of its values |
|
||||
}
|
||||
|
||||
@code{folding} is the general one: inside @code{expr} the accumulator's own name is the value so far.
|
||||
|
||||
@code{finding}, @code{someing}, @code{anding}, @code{oring} and @code{taking} stop the loop: the round that decides is the last, and the clauses after it in that round do not run. With @code{#:when}, or a loose @code{:when} in a comprehension, it finds the first value the condition holds for.
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
{finding x (:for x [3 5 8 9]) (:when (even? x))} ;; (Some 8)
|
||||
{finding x :when (> x 100) (:for x [3 5 8 9])} ;; None
|
||||
{someing (map-try-ref ages n) (:for n names)} ;; the age of the first name in ages, or None
|
||||
{anding (odd? x) (:for x [3 5 8 9])} ;; #f, after the round of 8
|
||||
{maximizing-by (string-length w) w (:for w (list "ab" "cde" "f"))} ;; (Some "cde")
|
||||
{grouping (% x 2) x (:for x [3 5 8 9])} ;; a map from 0 to (8) and 1 to (3 5 9)
|
||||
}|
|
||||
|
||||
It is a collector macro, written with @code{def/acc-clause}: a macro at the head of an accumulator's collector, which returns loop clauses that go where the @code{(:acc ...)} was. @code{(finding x)} returns @code{(someing (Some x))}, and @code{someing} returns a @code{folding} and a @code{(:finish ...)}.
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(def xs [3 9 2 7])
|
||||
|
||||
|
|
@ -1774,6 +1927,8 @@ A @code{string} is stored as UTF-8, and is always valid UTF-8. A @code{char} is
|
|||
(string-count s) ;; 10: characters, O(n). This is "how long is the text".
|
||||
}|
|
||||
|
||||
There is a third count too, of the characters a reader sees. An "é" can be one code point, or an e followed by a combining accent, and a flag is two code points. @code{string-grapheme-count} counts those; see the section on grapheme clusters below.
|
||||
|
||||
For the same reason there is no @code{string-ref} that takes an index. Finding the n:th character of a UTF-8 string means walking it, so walking is what you do: with a @code{loop}, a fold, or a cursor.
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
|
|
@ -1784,6 +1939,8 @@ For the same reason there is no @code{string-ref} that takes an index. Finding t
|
|||
|
||||
Characters are written @code{#\a}, @code{#\space}, @code{#\newline}. They can be compared with @code{<} and friends or @code{char=?}, converted with @code{char->int} and @code{int->char}, and classified with @code{char-alphabetic?}, @code{char-numeric?}, @code{char-whitespace?}, @code{char-upper-case?} and @code{char-lower-case?}.
|
||||
|
||||
In a string, a backslash begins an escape: @code{\n}, @code{\t}, @code{\r}, @code{\"} and @code{\\}, and @code{\u{...}}, a code point in 1 to 6 hex digits, as in @code{"caf\u{E9}"} or @code{"\u{1F600}"}. An interpolated string also has @code{\$}, a dollar sign that opens no hole. Any other escape is an error, so a backslash is written @code{\\}, or the text is written as a raw string, @code{"""..."""}, which has no escapes. A backslash at the end of a line continues the string on the next. A character can be written by its code point as well, as @code{#\xE9}.
|
||||
|
||||
@subsubsection{Common operations}
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
|
|
@ -1853,6 +2010,31 @@ The folds walk a string for you, and are usually simpler than a cursor:
|
|||
(count-vowels "Hello World") ;; 3
|
||||
}|
|
||||
|
||||
@subsubsection{Grapheme clusters}
|
||||
|
||||
What a reader takes for one character can be several @code{char}s: a letter and its accents, a flag, an emoji with a skin tone or a family of emoji joined by zero-width joiners, a Hangul syllable written in jamo, and CR LF. Unicode calls these grapheme clusters, and an editor's arrow keys and backspace move by them. @code{(std unicode grapheme)} finds them by Unicode's rules (UAX #29):
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(import (std unicode grapheme))
|
||||
|
||||
(def s "é🇸🇪\r\n")
|
||||
(string-count s) ;; 6
|
||||
(string-grapheme-count s) ;; 3
|
||||
(string->graphemes s) ;; ["é" "🇸🇪" "\r\n"]
|
||||
|
||||
;; Backspace: the string without its last cluster.
|
||||
(: drop-last-grapheme (-> string string))
|
||||
(defun (drop-last-grapheme s)
|
||||
(if (string-empty? s)
|
||||
s
|
||||
(substring s (string-cursor-start s)
|
||||
(string-cursor-prev-grapheme s (string-cursor-end s)))))
|
||||
|
||||
(drop-last-grapheme "ok 👍🏽") ;; "ok ": the skin tone goes with the thumb
|
||||
}|
|
||||
|
||||
@code{string-cursor-next-grapheme} and @code{string-cursor-prev-grapheme} take a cursor that is on a cluster boundary: the start, the end, or a cursor that a grapheme function returned. @code{string-cursor-grapheme-boundary?} tells whether a cursor that came from elsewhere is on one. A cluster has no limit on its length, since a letter can carry any number of accents, but a loop over a string by clusters takes O(n) time in either direction, so a text written to be slow cannot make it quadratic. @code{(std text)} has the same functions for texts.
|
||||
|
||||
@subsubsection{Slices}
|
||||
|
||||
@code{substring}, @code{string-trim} and @code{string-split} copy the text they answer. A slice is the same text without the copy: a string that shares the bytes of the string it was taken from. Only the forms ending in @code{/slice} make one:
|
||||
|
|
@ -1908,12 +2090,34 @@ Do not build strings by writing to a string port. Writing to a port is I/O as fa
|
|||
|
||||
@subsubsection{Converting to and from strings}
|
||||
|
||||
@code{->str} turns anything into a string, and @code{println} and interpolation use it. It is a trait, so your own types can decide what they look like (the card game did that for @code{Card}). For the basic types there are also named conversions:
|
||||
Two functions turn any value into a string:
|
||||
|
||||
@read-list{
|
||||
- @code{written} gives the value as the reader reads it, as Scheme's @code{write} does. A string is in quotes, a char is @code{#\a}, a number keeps the suffix of its type (@code{21L}), and a double always has a point (@code{3.0}). The REPL shows a result this way.
|
||||
- @code{displayed} gives the value for a person to read, as Scheme's @code{display} does. A string is its text, and a number has no suffix. @code{println}, @code{print} and interpolation use it.
|
||||
}
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(written "hej") ;; "\"hej\""
|
||||
(displayed "hej") ;; "hej"
|
||||
(written 21L) ;; "21L"
|
||||
(displayed 21L) ;; "21"
|
||||
(written (list "a" "b")) ;; "(\"a\" \"b\")"
|
||||
(displayed (list "a" "b")) ;; "(a b)"
|
||||
(written (Some (Tuple 1 "x"))) ;; "(Some (Tuple 1 \"x\"))"
|
||||
(println (Fruit (name "banana") (amount 5) (ripeness Rotten)))
|
||||
;; prints (Fruit (name "banana") (amount 5) (ripeness Rotten))
|
||||
}|
|
||||
|
||||
Every type you declare is written as you would build it. A type that prints differently for a person implements @code{Displayed}, as the card game did for @code{Card}; one that is written differently implements @code{Written}. The traits section has more. @code{->str} is deprecated: use @code{displayed}.
|
||||
|
||||
For the basic types there are also named conversions:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(int->string 42) ;; "42"
|
||||
(double->string 2.5) ;; "2.5"
|
||||
(->str 3.0) ;; "3"
|
||||
(displayed 3.0) ;; "3"
|
||||
(written 3.0) ;; "3.0"
|
||||
(string->int "42") ;; 42, and throws on anything that is not a number
|
||||
(string->double "1.5") ;; 1.5
|
||||
(char->string #\a) ;; "a"
|
||||
|
|
@ -1933,19 +2137,17 @@ For output where the layout matters, @code{(std fmt)} has two layers. The simple
|
|||
(println* ["Hello, " 42 ", ok? " #t]) ;; Hello, 42, ok? #t
|
||||
}|
|
||||
|
||||
The other one is a small layout language. A layout is a @code{(Vec Block)}, where a block is a string, a number, a character or one of the combinators, and @code{show} prints it:
|
||||
The other one is a small layout language, made of blocks. A string, an int or a character is a block, so is a vec of blocks, and so is what each of the combinators gives back. @code{show} prints a block:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(show ["[" (padded/left 6 ["foo"]) "]" nl]) ;; [ foo]
|
||||
(show ["[" (padded/right 6 ["foo"]) "]" nl]) ;; [foo ]
|
||||
(show [(numeric/comma 1234567.891) nl]) ;; 1,234,567.891
|
||||
(show ["[" (padded/left 6 "foo") "]" nl]) ;; [ foo]
|
||||
(show ["[" (padded/right 6 "foo") "]" nl]) ;; [foo ]
|
||||
(show [(numeric 1234567.891 #:comma 3) nl]) ;; 1,234,567.891
|
||||
(show [(numeric 3.14159 #:precision 2) nl]) ;; 3.14
|
||||
(render->string [(trimmed/right 5 ["abcdefgh"])]) ;; "abcde"
|
||||
(render->string (trimmed/right 5 "abcdefgh")) ;; "abcde"
|
||||
|
||||
(show [(joined/last (fun (s) (each [s]))
|
||||
(fun (s) (each ["and " s]))
|
||||
(list "a" "b" "c")
|
||||
[", "])
|
||||
(show [(joined/last BStr (fun (s) ["and " s])
|
||||
(list "a" "b" "c") ", ")
|
||||
nl]) ;; a, b, and c
|
||||
|
||||
;; tabular takes columns, and sizes each to its content.
|
||||
|
|
@ -1957,7 +2159,7 @@ The other one is a small layout language. A layout is a @code{(Vec Block)}, wher
|
|||
;; bo 7
|
||||
}|
|
||||
|
||||
The full set of combinators, paragraphs and settings is described in the reference for @code{(std fmt)}.
|
||||
The section on formatting text in "Writing programs" is a guide to the rest: paragraphs, tables, settings, and what to write when a layout does not compile. Every combinator is in the reference for @code{(std fmt)}.
|
||||
|
||||
@subsubsection{Regular expressions with (std rx)}
|
||||
|
||||
|
|
@ -1998,9 +2200,49 @@ The @code{Rx} and @code{RxIn} patterns use a regex inside a @code{match}. @code{
|
|||
|
||||
Define patterns at the top level, as above, rather than writing @code{#rx(...)} inside a clause. Otherwise the regex is recompiled at every call, which will tank performance.
|
||||
|
||||
@subsubsection{Text for editing with (std text)}
|
||||
|
||||
A string is immutable, and every edit copies all of it. For a large text that is edited in many places, such as an editor's buffer, @code{(std text)} has @code{Text}: a balanced tree of UTF-8 chunks, where inserting, deleting, splitting, appending and taking a substring take O(log n) time. An edit shares every chunk it does not change, so the old version stays valid and costs only what differs: undo is keeping the old texts.
|
||||
|
||||
The API is a string's. The functions a string has are there with @code{text-} for @code{string-}, positions are cursors, and the cursor functions take the text and the cursor. @code{text-length} is in bytes, as @code{string-length} is, and @code{text-count} counts characters, in O(1) time here. The tree also counts newlines, so lines are found in O(log n) time.
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(import (std text))
|
||||
|
||||
(def r (string->text "hello world\nsecond line"))
|
||||
(def c (text-cursor-forward r (text-cursor-start r) 5)) ;; O(log n), however far
|
||||
(def r2 (text-insert r c ","))
|
||||
(text->string r2) ;; "hello, world\nsecond line"
|
||||
(text->string (text-line r2 1)) ;; "second line"
|
||||
(text-cursor-line r2 (option-ref (text-search r2 "second"))) ;; 1
|
||||
(text->string r) ;; "hello world\nsecond line": unchanged
|
||||
}|
|
||||
|
||||
A cursor belongs to one text, and the text an edit returns needs cursors of its own. To keep a position across an edit, such as an editor's caret, keep its index: @code{text-cursor-index} gives it, and @code{text-cursor-forward} from the start of the new text finds it again.
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(def caret (option-ref (text-search r2 "world")))
|
||||
(def i (text-cursor-index r2 caret)) ;; 7
|
||||
(def r3 (text-insert r2 (text-cursor-start r2) "> "))
|
||||
(def caret3 (text-cursor-forward r3 (text-cursor-start r3) (+ i 2))) ;; still on "world"
|
||||
}|
|
||||
|
||||
A run of edits close together, such as typing, is faster through a @code{TransientText}, which edits in place, takes character indices, and gives a text back with @code{transienttext->text}. A @code{TextBuilder}, or the @code{texting} collector of a loop, builds a text in one pass. And @code{text-cursor-next-grapheme} and @code{text-cursor-prev-grapheme} step by grapheme clusters, as the arrow keys do:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(def t (text->transienttext r))
|
||||
(transienttext-insert! t 5 ",")
|
||||
(transienttext-insert! t 6 " my")
|
||||
(text->string (transienttext->text t)) ;; "hello, my world\nsecond line"
|
||||
|
||||
;; Backspace at the end of a text.
|
||||
(def e (string->text "ok 👍🏽"))
|
||||
(text->string (text-delete e (text-cursor-prev-grapheme e (text-cursor-end e)) (text-cursor-end e))) ;; "ok "
|
||||
}|
|
||||
|
||||
@subsection{Traits}
|
||||
|
||||
A trait is a set of functions that a type can implement. It is how bjolang does what other languages do with interfaces, type classes or overloading: @code{=} is a trait method, so is @code{->str}, and so are @code{length}, @code{fold} and @code{compare}.
|
||||
A trait is a set of functions that a type can implement. It is how bjolang does what other languages do with interfaces, type classes or overloading: @code{=} is a trait method, so is @code{displayed}, and so are @code{length}, @code{fold} and @code{compare}.
|
||||
|
||||
@subsubsection{Declaring and implementing a trait}
|
||||
|
||||
|
|
@ -2071,7 +2313,7 @@ A generic function that calls a trait method has to say that its type variable i
|
|||
|
||||
@code{describe-all} can now be called with a vec of anything that has a @code{Describe}, and calling it with anything else is a compile error at the call.
|
||||
|
||||
For @code{Eq} and @code{->str} you may leave the @code{where} out: the compiler adds them by itself when a function uses @code{=} or @code{->str} on a type variable.
|
||||
For @code{Eq}, @code{Written} and @code{Displayed} you may leave the @code{where} out: the compiler adds them by itself when a function uses @code{=}, @code{written} or @code{displayed} on a type variable.
|
||||
|
||||
@subsubsection{Associated types}
|
||||
|
||||
|
|
@ -2102,6 +2344,30 @@ A trait has exactly one implementor type. When a method needs another type that
|
|||
|
||||
This is how the prelude's own @code{Iterable}, @code{Collection} and @code{Refable} work, and why @code{length} and @code{fold} work on so many types.
|
||||
|
||||
@subsubsection{Implementations for particular type arguments}
|
||||
|
||||
An implementation may be written for a generic type at particular type arguments, and one type may have several, one for each:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(impl (Describe (List int))
|
||||
(defun (describe xs) "some numbers"))
|
||||
|
||||
(impl (Describe (List string))
|
||||
(defun (describe xs) "some words"))
|
||||
|
||||
(describe (list 1 2)) ;; "some numbers"
|
||||
(describe (list "a" "b")) ;; "some words"
|
||||
}|
|
||||
|
||||
The compiler picks the one whose arguments match. Two rules keep that choice unambiguous:
|
||||
|
||||
@itemlist{
|
||||
@item{Two implementations may not overlap. With @code{(List int)} already there, @code{(impl (Describe (List %a)) ...)} is refused, since a @code{(List int)} would then have two.}
|
||||
@item{The type has to be known where the call is. @code{(describe (list))} is an error, because an empty list could be either, and so is a call at @code{(List %a)} in a generic function: neither implementation is written for every element type. Give such a value an annotation, or write one implementation for @code{(List %a)} with a @code{where}, as in the next section.}
|
||||
}
|
||||
|
||||
Where only one implementation fits, it decides the type instead. With @code{(impl (Describe (List int)) ...)} and no other implementation for a list, @code{(describe (list))} is a call at @code{(List int)}, and a function with @code{(where (Describe %a))} called with @code{(list)} is too.
|
||||
|
||||
@subsubsection{Conditional and blanket implementations}
|
||||
|
||||
An implementation for a generic type can require something of its type variables, with a @code{where} after the head. A list can be described if its elements can:
|
||||
|
|
@ -2115,7 +2381,7 @@ An implementation for a generic type can require something of its type variables
|
|||
(describe (list Clubs Hearts)) ;; "clubs, hearts"
|
||||
}|
|
||||
|
||||
A blanket implementation is one for a bare type variable. It applies to every type that has no implementation of its own, and a more specific implementation always wins over it. Only the module that declares a trait may write its blanket:
|
||||
A blanket implementation is one for a bare type variable. It applies to every type that has no implementation of its own, and a more specific implementation always wins over it. A type whose head has implementations only for other arguments, such as a @code{(List bool)} beside the @code{(List int)} above, is an error rather than the blanket. Only the module that declares a trait may write its blanket, since a blanket is for every type and so for types the module did not declare:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(def/trait (Weight %a)
|
||||
|
|
@ -2131,16 +2397,77 @@ A blanket implementation is one for a bare type variable. It applies to every ty
|
|||
(weight "hello") ;; 5
|
||||
}|
|
||||
|
||||
@subsubsection{Eq, Ord and ->str}
|
||||
@subsubsection{Where an implementation is written}
|
||||
|
||||
Three traits from the prelude are worth knowing by heart, since the rest of the library leans on them.
|
||||
An implementation is written in the module that declares its trait, or in the one that declares its type. Every module that can name both the trait and the type then sees the implementation, so a call at a type means the same in every module. A module may implement its own traits for any type, and any trait for its own types:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(impl (Describe (List int)) ...) ;; fine: Describe is declared here
|
||||
(impl (Displayed Card) ...) ;; fine: Card is declared here
|
||||
(impl (Displayed (Tuple int string)) ;; refused: neither is declared here
|
||||
...)
|
||||
}|
|
||||
|
||||
A tuple, a type of the runtime such as @code{List}, and a .NET type are declared by no module, so only the module of a trait may implement it for one of them. To give such a type a trait from somewhere else, wrap it in a newtype of your own, as described below, and implement the trait for that. @code{#:via} gives the newtype the implementations the wrapped type already has.
|
||||
|
||||
Traits, types and implementations may be used above where they are written. A function may name a type that is declared further down, and call a method of a trait that is declared below it, and an implementation may stand above its trait.
|
||||
|
||||
@subsubsection{Traits that require other traits}
|
||||
|
||||
A trait may say that every type implementing it implements another trait too, with a @code{where} in the trait itself. Something that greets must have a name:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(def/trait (Named %a)
|
||||
(: name-of (-> %a string)))
|
||||
|
||||
(def/trait (Greet %a)
|
||||
(where (Named %a))
|
||||
(: greeting (-> %a string)))
|
||||
|
||||
(: introduce (-> %a string) (where (Greet %a)))
|
||||
(defun (introduce x) (str (name-of x) " says " (greeting x)))
|
||||
}|
|
||||
|
||||
@code{introduce} asks only for @code{Greet}, and may still call @code{name-of}: a type that can greet is known to have a name. An implementation of @code{Greet} for a type with no @code{Named} is a compile error at the implementation.
|
||||
|
||||
The prelude's @code{Ord} requires @code{Eq} this way, so a function with @code{(where (Ord %a))} can use @code{=} as well as @code{compare}. @code{Displayed} requires @code{Written} in the same way.
|
||||
|
||||
@subsubsection{Giving a newtype the traits of the type it wraps}
|
||||
|
||||
A newtype is the type it wraps when the program runs, so it can borrow that type's implementation of a trait as it is, with @code{#:via}:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(type (: Meters (Newtype double)))
|
||||
|
||||
(impl (Eq Meters) #:via double)
|
||||
(impl (Ord Meters) #:via double)
|
||||
(impl (Num Meters) #:via double) ;; + - * /
|
||||
(impl (Ordered Meters) #:via double) ;; < > <= >=
|
||||
|
||||
(+ (Meters 1.5) (Meters 2.0)) ;; (Meters 3.5)
|
||||
(+ (Meters 1.5) 2) ;; a number literal is a Meters too
|
||||
}|
|
||||
|
||||
@code{type/derive} writes these for you, for any trait, when the type is a newtype:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(type/derive (Eq Ord Num Ordered)
|
||||
(: Meters (Newtype double)))
|
||||
}|
|
||||
|
||||
A trait that should behave differently is written by hand instead. That is the other use of a newtype: the same data with a different behaviour, such as an @code{Eq} that ignores case on a @code{(Newtype string)}. Sets and maps of the newtype use that implementation, not the wrapped type's.
|
||||
|
||||
@subsubsection{Eq, Ord, Written and Displayed}
|
||||
|
||||
Four traits from the prelude are worth knowing by heart, since the rest of the library leans on them.
|
||||
|
||||
@read-table{
|
||||
| Trait | Methods | Gives you |
|
||||
|----------------+---------------------------------+------------------------------------------------------------------|
|
||||
| @code{Eq} | @code{=}, @code{eq-hash} | equality, and use as a key in maps and sets |
|
||||
| @code{Ord} | @code{compare} | @code{less?}, @code{least}, @code{list-sort}, @code{list-max}, ordered collections |
|
||||
| @code{->str} | @code{->str} | @code{println}, @code{print}, string interpolation |
|
||||
| Trait | Methods | Gives you |
|
||||
|-------------------+-----------------------------------------+------------------------------------------------------------------|
|
||||
| @code{Eq} | @code{=}, @code{eq-hash} | equality, and use as a key in maps and sets |
|
||||
| @code{Ord} | @code{compare} | @code{less?}, @code{least}, @code{list-sort}, @code{list-max}, ordered collections |
|
||||
| @code{Written} | @code{write-into}, @code{written} | the REPL's output, the failure text of @code{expect} |
|
||||
| @code{Displayed} | @code{display-into}, @code{displayed} | @code{println}, @code{print}, string interpolation |
|
||||
}
|
||||
|
||||
@code{Eq} and @code{Ord} can be derived with @code{type/derive}, as shown earlier. When you write them by hand, they must be written in the module that declares the type, because they are compiled into the type itself: they become its .NET @code{Equals}, @code{GetHashCode} and @code{CompareTo}, which is why a .NET dictionary or a sorted collection agrees with @code{=} and @code{compare}. @code{=} and @code{eq-hash} must agree: two values that are equal must have the same hash. @code{compare} returns a negative number, zero or a positive number.
|
||||
|
|
@ -2154,22 +2481,41 @@ Three traits from the prelude are worth knowing by heart, since the rest of the
|
|||
(hash-combine (eq-hash (record-ref c rank)) (eq-hash (record-ref c suit)))))
|
||||
}|
|
||||
|
||||
@code{->str} has a blanket implementation that uses .NET's @code{ToString}, which is why printing one of your own types shows its C# name until you implement it.
|
||||
The compiler writes a @code{Written} for every type you declare, so a value prints as you would build it: @code{(Card (rank Queen) (suit Hearts))}, @code{(Pip 7)}, @code{Hearts}. A generic type is written when its type arguments are. An @code{#:opaque} type is written as @code{#<Name>}, and a function as @code{#<procedure>}, wherever it is: @code{(println (Some (fun (x) (+ x 1))))} prints @code{(Some #<procedure>)}, and so does a field that holds one, or a function at the REPL's prompt. Every function type has the head @code{Procedure}, so a trait of your own can have an implementation for functions, @code{(impl (Describe Procedure) ...)}, which applies to all of them. A blanket does not reach them, which is why @code{(= f g)} on two functions is still refused. @code{Displayed} has a blanket implementation that displays a value as it is written.
|
||||
|
||||
To print a type your own way, implement @code{Displayed} for the text a person reads, as the card game did, or @code{Written} to change the written form too. The method to give is @code{display-into} (or @code{write-into}), which adds the text to a string builder; @code{displayed} and @code{written} then come with the trait:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(type (: Money (Union (: Kr int))))
|
||||
|
||||
(impl (Displayed Money)
|
||||
(defun (display-into m b)
|
||||
(match m ((Kr n) (stringbuilder-add-string! b #"${n} kr")))))
|
||||
|
||||
(println (Kr 42)) ;; 42 kr
|
||||
(written (Kr 42)) ;; "(Kr 42)"
|
||||
}|
|
||||
|
||||
A container that holds other values calls @code{write-into} or @code{display-into} on them with the same builder. @code{elements-print-into} and @code{entries-print-into} from the prelude lay out the elements of a collection, or the entries of a map, for you.
|
||||
|
||||
@code{->str} is deprecated. It still works, through @code{displayed}, but each use gives a warning.
|
||||
|
||||
@subsubsection{Values of different types in one collection: dyn}
|
||||
|
||||
A list holds values of one type. When you need a collection of different types that all implement the same trait, pack each value as a @code{(dyn Trait)}:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(: render-all (-> (List (dyn ->str)) (List string)))
|
||||
(defun (render-all xs) (list-map ->str xs))
|
||||
(: render-all (-> (List (dyn Displayed)) (List string)))
|
||||
(defun (render-all xs) (list-map displayed xs))
|
||||
|
||||
(render-all (list (dyn ->str 1)
|
||||
(dyn ->str "two")
|
||||
(dyn ->str (Card (rank Queen) (suit Hearts)))))
|
||||
(render-all (list (dyn Displayed 1)
|
||||
(dyn Displayed "two")
|
||||
(dyn Displayed (Card (rank Queen) (suit Hearts)))))
|
||||
;; '("1" "two" "Q♥")
|
||||
}|
|
||||
|
||||
A @code{(dyn T)} implements the traits that @code{T} requires as well, and the ones those require, through the value it holds. With @code{Greet} and @code{Named} from above, a @code{(dyn Greet)} can be given to @code{introduce}, which calls @code{name-of}, and to any function that asks for @code{(where (Named %a))}. So a trait cannot be packed if a trait it requires cannot be packed, or has associated types.
|
||||
|
||||
Packing is always explicit, and a @code{dyn} cannot be turned back into the value it came from. It is the exception rather than the rule: most code is better served by a union.
|
||||
|
||||
@subsubsection{Traits that are .NET interfaces}
|
||||
|
|
@ -2230,22 +2576,36 @@ Nothing about @code{list-sort} knows about cards. It asks for @code{(Ord %a)}, a
|
|||
|
||||
@subsubsection{The types}
|
||||
|
||||
There are eight numeric types, each a .NET primitive:
|
||||
The numeric types are the .NET ones:
|
||||
|
||||
@read-table{
|
||||
| Type | Range | Type | Range |
|
||||
|----------------+------------------------------+----------------+------------------------|
|
||||
| @code{byte} | 0 … 255 | @code{uint} | 0 … 2^32−1 |
|
||||
| @code{short} | −32 768 … 32 767 | @code{long} | −2^63 … 2^63−1 |
|
||||
| @code{ushort} | 0 … 65 535 | @code{ulong} | 0 … 2^64−1 |
|
||||
| @code{int} | about ±2.1 billion | @code{double} | 64-bit floating point |
|
||||
| Type | Range | Type | Range |
|
||||
|----------------+------------------------------+----------------+---------------------------|
|
||||
| @code{byte} | 0 … 255 | @code{uint} | 0 … 2^32−1 |
|
||||
| @code{short} | −32 768 … 32 767 | @code{long} | −2^63 … 2^63−1 |
|
||||
| @code{ushort} | 0 … 65 535 | @code{ulong} | 0 … 2^64−1 |
|
||||
| @code{int} | about ±2.1 billion | @code{double} | 64-bit floating point |
|
||||
| @code{bigint} | any integer | @code{float} | 32-bit floating point |
|
||||
| @code{int128} | −2^127 … 2^127−1 | @code{decimal} | 28 digits, exact decimals |
|
||||
| @code{uint128} | 0 … 2^128−1 | @code{rational} | exact fractions |
|
||||
}
|
||||
|
||||
There is no @code{float} and no @code{decimal}. A @code{char} is not a number: it can be compared and converted, but not added.
|
||||
All but one are the .NET ones. @code{rational} is bjolang's own, an exact fraction over @code{bigint}, and a number like the others: @code{+ - * /} and the comparisons work on it, and a literal at it is exact, so @code{0.1} is one tenth and not the double nearest to it. It prints as @code{1/3}. @code{(std rational)} has its operations by name, as @code{rational+} and @code{rational->double}.
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(: third rational)
|
||||
(def third (/ 1 3))
|
||||
|
||||
(* third 0.3) ;; 1/10, exactly
|
||||
(= (* third 3) 1) ;; #t
|
||||
(cast double third) ;; 0.3333333333333333
|
||||
}|
|
||||
|
||||
A @code{char} is not a number: it can be compared and converted, but not added.
|
||||
|
||||
@subsubsection{Writing numbers}
|
||||
|
||||
A number with a suffix is of that type. A decimal point or an exponent makes it a @code{double}:
|
||||
A number with a suffix is of that type. A decimal point or an exponent makes it a real number, which is a @code{double}, a @code{float} or a @code{decimal}, and never an integer:
|
||||
|
||||
@read-table{
|
||||
| Written | Type |
|
||||
|
|
@ -2256,11 +2616,14 @@ A number with a suffix is of that type. A decimal point or an exponent makes it
|
|||
| @code{21u} | @code{uint} |
|
||||
| @code{21L} | @code{long} |
|
||||
| @code{21UL} | @code{ulong} |
|
||||
| @code{21d} @code{2.5} @code{1e3} | @code{double} |
|
||||
| @code{21d} @code{2.5d} | @code{double} |
|
||||
| @code{21M} @code{2.5M} | @code{decimal} |
|
||||
| @code{21I} | @code{bigint} |
|
||||
| @code{2.5} @code{1e3} | a real type, as the context says |
|
||||
| @code{0x2A} @code{0b101010} | 42, of whatever type the context says |
|
||||
}
|
||||
|
||||
A number without a suffix has no type of its own. It takes the type of wherever it is used, and is an @code{int} only when nothing says otherwise:
|
||||
A number without a suffix has no type of its own. It takes the type of wherever it is used, and is an @code{int}, or a @code{double} if it is real, only when nothing says otherwise:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(: doubled (-> ushort ushort))
|
||||
|
|
@ -2270,9 +2633,12 @@ A number without a suffix has no type of its own. It takes the type of wherever
|
|||
|
||||
(let ((start 5))
|
||||
(+ start 3L)) ;; 8L: start was a long all along
|
||||
|
||||
(: tenth decimal)
|
||||
(def tenth 0.1) ;; a decimal, so (+ tenth 0.2) is exactly 0.3
|
||||
}|
|
||||
|
||||
A literal that does not fit the type it ends up with is a compile error. @code{(doubled 99999)} says that 99999 does not fit in a @code{ushort}.
|
||||
A literal that does not fit the type it ends up with is a compile error. @code{(doubled 99999)} says that 99999 does not fit in a @code{ushort}, and @code{(doubled 2.5)} that 2.5 has a fraction.
|
||||
|
||||
@subsubsection{Arithmetic}
|
||||
|
||||
|
|
@ -2390,7 +2756,7 @@ If a function only compares values, use @code{(where (Ord %a))} instead. It work
|
|||
@codeblock[#:lang "bjolang"]|{
|
||||
(import (std maths))
|
||||
|
||||
(sqrt 9) ;; 3.0: the int 9 widens to a double at the call
|
||||
(sqrt 9) ;; 3.0: the 9 is a double, since sqrt takes one
|
||||
(pow 2.0 10.0) ;; 1024.0
|
||||
(floor -2.5) ;; -3.0
|
||||
(truncate -2.5) ;; -2.0
|
||||
|
|
@ -2403,3 +2769,118 @@ If a function only compares values, use @code{(where (Ord %a))} instead. It work
|
|||
The logarithms are @code{loge} (natural), @code{log2}, @code{log10} and @code{(log-base x b)}. The name @code{log} is taken by the logging function of the prelude.
|
||||
|
||||
|
||||
|
||||
@subsection{Units of measure}
|
||||
|
||||
A number can carry a dimension in its type. A @code{(double m/s)} is a speed, a @code{(double m)} is a length, and the compiler refuses to add the two. The checking is all at compile time: a @code{(double m/s)} is a plain @code{double} at run time, and a conversion between units is a constant the compiler works out.
|
||||
|
||||
@subsubsection{Quantities}
|
||||
|
||||
A quantity is written in angle brackets, a number and then a unit:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(import (std units))
|
||||
|
||||
(def g <9.80665 m/s^2>) ;; a (double m/s^2)
|
||||
(def limit <120 km/h>) ;; a (double m/s): 33.33…
|
||||
(def width <3 ft>) ;; a (double m): 0.9144
|
||||
}|
|
||||
|
||||
Each dimension has a base unit, and a quantity is kept in it: a length in metres, a time in seconds, a speed in metres per second. @code{<120 km/h>} is converted to metres per second when the program is compiled, and is one constant in the code that comes out. So every length is the same type, whatever unit it was written in, and @code{(+ <1 m> <1 ft>)} is 1.3048 metres.
|
||||
|
||||
The unit is written as GNU @code{units} writes one: @code{kg m/s^2} is kilograms times metres per second squared, a space or a @code{*} multiplies, @code{/} divides, and @code{^} raises, with a negative or a fractional power as @code{s^-2} or @code{Hz^(-1/2)}. Everything after @code{/} up to the next @code{/} or @code{*} is below the line, so @code{m/s kg} is m/(s·kg). Prefixes go on any unit: @code{km}, @code{mg}, @code{GHz}, @code{KiB}. The number is read exactly, and may be a fraction: @code{<1|3 h>} is twenty minutes, and @code{<1e-3 km>} is a metre. A @code{<} with a digit right after it starts a quantity, so @code{(< 1 2)} is still a comparison, but @code{(<1 2)} is not.
|
||||
|
||||
@subsubsection{Types}
|
||||
|
||||
A type with a unit is a number type and a unit: @code{(double m/s)}, @code{(long cent)}, @code{(double kg m^2/s^2)}. A type names base units, so a field of a record is @code{(double m)} even when the numbers in it are thought of as kilometres. A unit that is only a name for base units can be written too: @code{(double N)} is @code{(double kg m/s^2)}. One that has a factor cannot, because a @code{(double km)} would be a number in metres with a lie on it:
|
||||
|
||||
@codeblock[#:lang "text"]|{
|
||||
Type Error at trip.bjo:4:10: 'km' is 1000 m, and a type names base units only:
|
||||
write (double m), and (number-in x km) where a number in km is needed.
|
||||
}|
|
||||
|
||||
@code{<m/s>} is the unit with the number type its dimension keeps it in, which is @code{double} for SI. Records, unions, signatures and @code{let} take these types as they take any other:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(type (: Leg (Record (: distance (double m))
|
||||
(: climb (double m))
|
||||
(: speed (double m/s)))))
|
||||
|
||||
(def leg (Leg (distance <38 km>) (climb <800 ft>) (speed <15 mph>)))
|
||||
|
||||
(: hours (-> Leg (double s)))
|
||||
(defun (hours l) (/ (.distance l) (.speed l))) ;; m / (m/s) is s
|
||||
}|
|
||||
|
||||
@subsubsection{Arithmetic}
|
||||
|
||||
@code{+}, @code{-} and the comparisons take two numbers of the same unit, and @code{*} and @code{/} multiply and divide the units, so @code{(* <2 m> <3 m>)} is a @code{(double m^2)}. @code{sqrt} takes the root of the unit too: the square root of an area is a length. A number with no unit scales: @code{(* 2 g)} is still an acceleration.
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(+ (.distance leg) (.climb leg)) ;; a length: 38243.84 m
|
||||
(+ (.distance leg) (.speed leg)) ;; a type error: a length and a speed
|
||||
(* <2 m> <3 m>) ;; 6 m^2
|
||||
(sqrt (* <2 m> <8 m>)) ;; 4 m
|
||||
}|
|
||||
|
||||
A plain number has no unit, so it cannot be compared with a length. The error says what to write instead. Zero is the exception: it is a number of every unit, so @code{(> (.climb leg) 0)} works.
|
||||
|
||||
@codeblock[#:lang "text"]|{
|
||||
Type Error at trip.bjo:9:22: '1' is a plain number, and it is being used where a
|
||||
(double m) is wanted. Write <1 m>, or a unit of the same dimension.
|
||||
}|
|
||||
|
||||
A function that works at any unit says so with a unit variable, written as a type variable is:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(: larger (-> (double %u) (double %u) (double %u)))
|
||||
(defun (larger a b) (if (> a b) a b))
|
||||
|
||||
(larger <1 km> <900 m>) ;; 1000 m: lengths are kept in metres
|
||||
(larger <3 s> <2 s>) ;; 3 s
|
||||
|
||||
(: rms (-> (double %u) (double %u) (double %u)))
|
||||
(defun (rms a b) (sqrt (/ (+ (sqr a) (sqr b)) 2.0))) ;; sqr: %u to %u^2
|
||||
}|
|
||||
|
||||
@code{(num %c %u)} is a number of any type at any unit, for a function that is generic in both. A function that is generic over @code{Num} does not take a number with a unit, because @code{Num} allows multiplication and its type promises that the unit stays: @code{(sqr x)} on metres is square metres. @code{abs}, @code{min}, @code{max}, @code{clamp}, @code{sign}, @code{zero?}, @code{sqr} and @code{positive?} take any unit. @code{summing} does not yet.
|
||||
|
||||
@subsubsection{Getting the number out}
|
||||
|
||||
@code{(number-in x unit)} is the number @code{x} is in a unit, as a plain number: what a quantity is when it is printed, written to a file or given to .NET. The unit must have @code{x}'s dimension. The other way, a plain number gets a unit by multiplication:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(number-in (hours leg) h) ;; 1.574: the leg takes an hour and a half
|
||||
(number-in (.distance leg) km) ;; 38.0
|
||||
(number-in <45 deg> rad) ;; 0.785…
|
||||
(* 2.5 <1 km>) ;; a length: 2500 m
|
||||
(number-in (.distance leg) s) ;; a type error: a length, not a time
|
||||
}|
|
||||
|
||||
@code{number-in} is one multiplication by a constant, and none when the unit is the base. @code{cast} also takes the unit off, but it does not convert: it is right only for a number already in the base unit.
|
||||
|
||||
@subsubsection{Dimensions and units of your own}
|
||||
|
||||
Nothing about SI is built into the compiler. @code{(std units)} is a module of declarations, and a program can make its own the same way, with or without it:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(def/dimension money #:base cent #:carrier long)
|
||||
(def/unit EUR <100 cent>)
|
||||
(def/prefix k 1000)
|
||||
|
||||
(: price (long cent))
|
||||
(def price <12.50 EUR>) ;; 1250L
|
||||
(number-in price EUR) ;; a compile error: it would divide a long by 100
|
||||
}|
|
||||
|
||||
@read-list{
|
||||
- @code{(def/dimension name #:base unit)} declares a dimension and its base unit. @code{#:carrier} says which number type its quantities are when nothing else says: @code{double} when it is left out. A type can always say otherwise, as @code{(double cent)} does.
|
||||
- @code{(def/unit name quantity)} declares a unit as an amount of units already declared: @code{(def/unit mi <5280 ft>)}, @code{(def/unit N <1 kg m/s^2>)}. A unit with no dimension is a plain number: @code{(def/unit % <1|100>)}.
|
||||
- @code{(def/prefix name number)} declares a prefix that goes on every unit.
|
||||
}
|
||||
|
||||
Units belong to the module that declares them and to the modules that import it. Two modules that each declare an @code{m} have two different units, as two types called @code{Point} are two types.
|
||||
|
||||
A literal at an integer type has to come out whole: @code{<0.001 EUR>} at a @code{(long cent)} is a compile error, and so is @code{number-in} to a coarser unit, which would divide. At @code{rational} every conversion is exact, so a program that must not round declares its dimensions with @code{#:carrier rational}: there, @code{<1 km/h>} is exactly 5/18 metres per second, and back in kilometres per hour it is exactly 1.
|
||||
|
||||
The module reference for @link["modules/std/units.html"]{@code{(std units)}} lists the units it declares, and has a library for units at run time, for a unit that is read as text.
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -12,11 +12,29 @@ For more details, see @link["modules/std/prelude.html"]{@code{(std prelude)}}.
|
|||
Numbers beyond the operators. Integer division has Racket's names: @code{quotient} and @code{remainder} are what @code{/} and @code{%} do, and @code{modulo} takes the sign of the divisor, so @code{(modulo -1 10)} is 9. There are @code{gcd}, @code{lcm}, an integer @code{expt} and an exact @code{integer-sqrt} at every integer type, the @code{exact-} roundings from a double to an int, and the rest of @code{System.Math} over doubles. The prelude has @code{abs}, @code{min}, @code{max} and @code{clamp} from here without an import.
|
||||
For more details, see @link["modules/std/maths.html"]{@code{(std maths)}}.
|
||||
|
||||
@subsection{std/rational}
|
||||
|
||||
Exact fractions over @code{bigint}. @code{Rational} is the built-in @code{rational} type, kept in lowest terms with a positive denominator so equal fractions are equal values. @code{(rational n d)} constructs a fraction, @code{rational-num} and @code{rational-den} take it apart, and @code{rational+}, @code{rational*}, @code{rational-recip} and @code{rational-expt} work alongside the standard arithmetic operators. @code{string->rational} reads both @code{"1|60"} and decimal text such as @code{"0.3048"}, and @code{rational->double} and @code{rational->decimal} convert back.
|
||||
For more details, see @link["modules/std/rational.html"]{@code{(std rational)}}.
|
||||
|
||||
@subsection{std/units}
|
||||
|
||||
Units of measure, both at compile time and at run time. Importing the module declares the SI base dimensions and @code{information} (@code{b}), the SI and binary prefixes, and about 270 units with @code{def/dimension}, @code{def/prefix} and @code{def/unit}—the definitions that quantity literals like @code{<120 km/h>}, unit-annotated types like @code{(double m/s)}, and @code{number-in} use at compile time and erase at run time. For units that arrive as text at run time, @code{string->measurement}, @code{measurement-in} and @code{convert-query} (e.g. @code{(convert-query "6000 m + 50 ft in mi")}) parse, check dimensions and convert against a runtime unit table.
|
||||
For more details, see @link["modules/std/units.html"]{@code{(std units)}}.
|
||||
|
||||
@subsection{std/array and std/simd}
|
||||
|
||||
Two modules for numbers in bulk, with the CPU's vector instructions. @code{(std array)} has whole-array operations: @code{array-sum}, @code{array-dot}, @code{array-min}, @code{array-max}, @code{array-add!}, @code{array-scale!}, @code{array-count}, @code{array-index-of} and @code{array-fill!}. Each is one loop in the runtime, which works on as many elements per instruction as a vector register holds when the element is a primitive number, and one at a time for a type such as @code{bigint}. At @code{double}, a sum adds lane by lane, so its last bits can differ from a left fold. @code{(std simd)} has the vectors themselves, for the loops that the kernels do not cover. @code{(Simd128 %a)} and @code{(Simd256 %a)} are .NET's @code{Vector128<T>} and @code{Vector256<T>}, with a name per element type: @code{Float64x4} is four doubles, @code{UInt8x32} is 32 bytes. The operations are the methods of one trait, @code{Simd}, at both widths: @code{simd-add}, @code{simd-mul}, the comparisons @code{simd-lt} and the others, which give masks, @code{simd-select}, @code{simd-count-true}, @code{simd-sum} and more. A vector is made with @code{simd256-load}, @code{simd128-splat} or @code{simd256-zero}, and @code{simd256-whole} says where the elements after the last whole vector start. A 128-bit vector is fast on every x86-64 and ARM64 CPU. A 256-bit vector needs AVX2, and @code{simd256-accelerated?} says whether the CPU has it. The section on performance in "Writing programs" says when vectors pay.
|
||||
For more details, see @link["modules/std/array.html"]{@code{(std array)}} and @link["modules/std/simd.html"]{@code{(std simd)}}.
|
||||
|
||||
@subsection{std/parallel and std/combine}
|
||||
|
||||
Data-parallel work across CPU cores on dedicated compute threads. @code{(std parallel)} splits any @code{Chunkable} collection (@code{Range}, @code{Vec}, @code{Array}, @code{IArray}, @code{Map}, @code{HashSet}, @code{OrderedMap} and @code{OrderedSet}) into parts without copying elements. @code{in-parts} runs a function on each part and returns a vector of the part results; @code{in-parallel} joins the part results in order using @code{Combinable} from @code{(std combine)}; and @code{par-map}, @code{par-filter} and @code{par-for-each} operate over a whole collection. For an array, @code{part->span} gives each worker a writable @code{(Span %a)} over its own non-overlapping slice so an array can be updated in place across cores without locks. @code{(std combine)} provides the associative @code{Combinable} trait (@code{combine} and @code{combine-all}) for types with one natural ordered combination: @code{Vec}, @code{List}, @code{IArray}, @code{string}, sets and tuples.
|
||||
For more details, see @link["modules/std/parallel.html"]{@code{(std parallel)}} and @link["modules/std/combine.html"]{@code{(std combine)}}.
|
||||
|
||||
@subsection{std/fmt}
|
||||
|
||||
Formatting in Bjolang is divided into two layers: interpolation and layout.
|
||||
Interpolation provides a simple way to combine mixed scalar types into strings or print them directly using @code{println*} and @code{str*}.
|
||||
The layout layer provides a composable block algebra for more complex text formatting, such as padding, aligning, wrapping paragraphs, and laying out tables.
|
||||
Formatting in two layers: interpolation and layout. @code{println*} prints strings, ints, doubles, chars and bools written in one vec. The layout layer is made of blocks: a @code{Block} is one piece of output, and every combinator takes its content as a block and gives back a block. A string, an int and a character are blocks, and so is a vec of blocks, such as @code{["x = " 7 nl]}. With them you pad, cut and align text, wrap and justify paragraphs, format numbers, and lay out tables with borders, a header, and columns that fit the width. The section on formatting text in "Writing programs" is a guide, with what goes in the brackets and what to write when it does not compile.
|
||||
For more details, see @link["modules/std/fmt.html"]{@code{(std fmt)}}.
|
||||
|
||||
@subsection{std/rx}
|
||||
|
|
@ -24,6 +42,21 @@ For more details, see @link["modules/std/fmt.html"]{@code{(std fmt)}}.
|
|||
Bjolang provides a built-in regular expression engine. Unlike languages that use strings for regex (like @code{"[a-z]+"}), Bjolang uses structural S-expressions. This means you never have to double-escape characters, and the compiler validates your patterns at compile time. Built-in character sets and anchors are written as keywords (e.g., @code{:bos}, @code{:digit}), and operations that group or repeat patterns are function-like lists (e.g., @code{(seq ...)}).
|
||||
For more details, see @link["modules/std/rx.html"]{@code{(std rx)}}.
|
||||
|
||||
@subsection{std/scan}
|
||||
|
||||
Reading a line by a pattern, after OCaml's @code{Scanf}. The pattern is a quoted list of what the line holds, in order: @code{(scan "3-17" '(long "-" long))} is 3 and 17, and @code{'(int "x" int ": " int ... #:sep " ")} reads @code{"12x5: 1 0 3"} as two ints and a vec of them. There are items for numbers, a character, a word, the rest of the line, a run of given characters and the text up to one, with a width, a skip, a repetition, an option and a choice. The type of the result comes from the pattern, so @code{'(int "," int)} gives a @code{(Tuple int int)}. The macro compiles the pattern into straight code over the line's bytes, and a pattern of numbers and strings allocates nothing. The whole line must match. @code{try-scan} gives an @code{Err} that says at which column it failed, instead of raising. A scan does not search and does not backtrack: use @code{(std rx)} to find text in a line.
|
||||
For more details, see @link["modules/std/scan.html"]{@code{(std scan)}}.
|
||||
|
||||
@subsection{std/text}
|
||||
|
||||
Text that is cheap to edit anywhere, for an editor's buffer or any large text that changes in many places. A @code{Text} is a balanced tree of UTF-8 chunks: inserting, deleting, splitting, appending, taking a substring and finding a line take O(log n) time, and an edit shares everything it does not change, so old versions stay valid for undo. The API is a string's, with @code{text-} for @code{string-}: positions are cursors, the cursor functions take the text and the cursor, and no function takes a byte offset. @code{text-count} is O(1), @code{text-cursor-forward} moves any number of characters in O(log n), and @code{text-cursor-index} gives a cursor's index to carry across an edit. A @code{TransientText} edits in place for a run of edits such as typing, and @code{TextBuilder} and the @code{texting} collector build a text in one pass. @code{text-cursor-next-grapheme} and the others step by grapheme clusters.
|
||||
For more details, see @link["modules/std/text.html"]{@code{(std text)}}.
|
||||
|
||||
@subsection{std/unicode/grapheme}
|
||||
|
||||
Grapheme clusters, the characters a reader sees, by Unicode's rules (UAX #29): a letter and its accents, a flag, an emoji sequence, CR LF. @code{string-cursor-next-grapheme} and @code{string-cursor-prev-grapheme} move a cursor by one, as an editor's arrow keys and backspace do, and @code{string-grapheme-count} and @code{string->graphemes} count and split. A cluster has no limit on its length, but a loop by clusters takes O(n) time in either direction, so long runs of accents or flags cannot make it quadratic. The rules are two state machines over characters, which other containers can drive with their own cursors: @code{(std text)} does, for texts.
|
||||
For more details, see @link["modules/std/unicode/grapheme.html"]{@code{(std unicode grapheme)}}.
|
||||
|
||||
@subsection{std/http}
|
||||
|
||||
The @code{std/http} module allows you to build and send HTTP requests. Sending a request three ways — blocking, suspending, or as an event — is the only thing that differs between the entry points. There is no C# in this module: @code{System.Net.Http} is reached with @code{import/extern}, and the response body is an ordinary @code{TextInputPort}.
|
||||
|
|
@ -36,7 +69,7 @@ For more details, see @link["modules/std/url.html"]{@code{(std url)}}.
|
|||
|
||||
@subsection{std/run}
|
||||
|
||||
The @code{std/run} module provides a way to run external programs. A form is one thing to run, written as a quoted literal, like @code{'(cat "hej.txt")}. You can connect programs in a pipe with @code{'(pipe (cat "a") (wc -l))}, and redirect input and output to files. Redirections can nest, and you can even splice computed arguments or write stages in Bjolang.
|
||||
The @code{std/run} module provides a way to run external programs. A form is one thing to run, written as a quoted literal, like @code{'(cat "hej.txt")}. You can connect programs in a pipe with @code{'(pipe (cat "a") (wc -l))}, and redirect input and output to files. Redirections can nest, and you can even splice computed arguments or write stages in Bjolang. @code{run/stream} gives a program's output as a @code{Stream}: each loop over it runs the program, and the program is killed however the loop ends.
|
||||
For more details, see @link["modules/std/run.html"]{@code{(std run)}}.
|
||||
|
||||
@subsection{std/random}
|
||||
|
|
@ -44,6 +77,16 @@ For more details, see @link["modules/std/run.html"]{@code{(std run)}}.
|
|||
The random module provides a ChaCha20 generator, seeded with 256 bits from the OS CSPRNG, with one generator per thread. The default path locks nothing and shares nothing, making it safe and fast on a bjoroutine. The ambient source has no state to race on, so drawing from multiple threads is efficient. You can generate random integers and more.
|
||||
For more details, see @link["modules/std/random.html"]{@code{(std random)}}.
|
||||
|
||||
@subsection{std/uuid}
|
||||
|
||||
Uuids as RFC 9562 specifies them. @code{uuid-v4} is random, for an identifier that must tell nothing. @code{uuid-v7} starts with the time, for a database key: new keys go at the end of an index, and keys sort by when they were made, and the ones made by one process always increase. @code{uuid-v5} is made from a namespace and a name, so the same input gives the same uuid. A @code{Uuid} is 16 bytes and compares as its bytes do, which is also the order of its text and of Postgres' @code{uuid}. @code{uuid->string} writes the one text form, and @code{string->uuid} reads it in either case. The random bits come from @code{current-random} and the time from @code{current-clock}, so a test can make the same uuids in every run.
|
||||
For more details, see @link["modules/std/uuid.html"]{@code{(std uuid)}}.
|
||||
|
||||
@subsection{std/crypto/hash}
|
||||
|
||||
Hashes, HMAC and password hashing, from .NET's @code{System.Security.Cryptography}. @code{hash-bytes}, @code{hash-string} and @code{hash-file} make a digest, SHA-256 unless @code{#:algorithm} says otherwise, and @code{make-hasher} makes one a piece at a time. @code{hmac-bytes} and @code{hmac-string} sign a message with a key. A digest is fast, so it is not a password hash: @code{password-hash} uses PBKDF2 with a random salt and gives a PHC string, which holds the algorithm and the iteration count, so @code{password-verify} needs only the password and the string, and @code{password-needs-rehash?} says which to replace after the count is raised. A password hash takes a few hundred milliseconds, and in a bjoroutine it runs on a thread of its own. Compare secrets with @code{constant-time-equal?}, not @code{=}.
|
||||
For more details, see @link["modules/std/crypto/hash.html"]{@code{(std crypto hash)}}.
|
||||
|
||||
@subsection{std/atomic}
|
||||
|
||||
An atomic is a cell that threads can read and write without a lock. @code{(make-atomic v)} makes one of any type, and @code{atomic-ref}, @code{atomic-set!}, @code{atomic-swap!}, @code{atomic-compare-and-swap!} and @code{atomic-update!} work on it. For @code{int}, @code{uint}, @code{long} and @code{ulong} there are also @code{atomic-increment!}, @code{atomic-decrement!}, @code{atomic-add!} and @code{atomic-sub!}, which compile to direct calls to @code{System.Threading.Interlocked} and wrap on overflow. Swap and compare-and-swap return the value from before the call; the other operations that change the atomic return the new value. The width of a counter comes from type inference, so write @code{(make-atomic 0L)} for a long counter: @code{(make-atomic 0)} is an int.
|
||||
|
|
@ -79,6 +122,11 @@ For more details, see @link["modules/std/effect.html"]{@code{(std effect)}}.
|
|||
Persistent collections beside the prelude's @code{Map}: an update returns a new collection and does not change the old one. @code{(std hashset)} has the unordered @code{HashSet}, a CHAMP trie that compares elements with @code{Eq}. @code{(std orderedset)} and @code{(std orderedmap)} have @code{OrderedSet} and @code{OrderedMap}, B-trees kept in the order of @code{compare}. They add what the order gives: @code{-min}, @code{-max}, @code{-successor}, @code{-predecessor} and the range walks @code{-range}, @code{-from} and @code{-until}. Each collection has a builder, which makes it in one pass, and a transient, which edits it in place and gives it back as a persistent collection in O(1).
|
||||
For more details, see @link["modules/std/hashset.html"]{@code{(std hashset)}}, @link["modules/std/orderedset.html"]{@code{(std orderedset)}} and @link["modules/std/orderedmap.html"]{@code{(std orderedmap)}}.
|
||||
|
||||
@subsection{std/priority-queue}
|
||||
|
||||
A persistent priority queue, least priority first. A @code{(PriorityQueue a p)} holds elements under priorities, and orders the priorities, so the elements need no order of their own. @code{priorityqueue-empty} orders priorities by their @code{Ord}, and @code{priorityqueue-by} by a comparison you give it. Adding or removing gives a new queue and leaves the old one as it was. It is a pairing heap: peeking, adding and @code{priorityqueue-merge} are O(1), and @code{priorityqueue-remove-min} is O(log n) amortised. That bound assumes each queue is used once. Call @code{priorityqueue-balance} on a queue you keep and remove from many times. Entries of equal priority come out in the order they went in. There is a transient and a builder, as for the other persistent collections. For a queue that is used in one place and never shared, @code{(std mutable heap)} is faster.
|
||||
For more details, see @link["modules/std/priority-queue.html"]{@code{(std priority-queue)}}.
|
||||
|
||||
@subsection{std/mutable}
|
||||
|
||||
Collections that change in place. Use them for a cache, an index, a worklist or a scratch buffer, where you do not need old versions. @code{(std mutable vec)}, @code{(std mutable map)}, @code{(std mutable set)} and @code{(std mutable heap)} are the .NET @code{List<T>}, @code{Dictionary<K,V>}, @code{HashSet<T>} and @code{PriorityQueue<T,P>} themselves, not wrappers, so .NET code that takes those types accepts them as they are. They compare with .NET's equality and order. @code{(std mutable deque)} is a double-ended queue with O(1) amortized push and pop at both ends. None of them has a lock.
|
||||
|
|
@ -89,9 +137,28 @@ For more details, see @link["modules/std/mutable/vec.html"]{@code{(std mutable v
|
|||
An inbox is how .NET code gives work to Bjolang. A thread that is not a fiber, such as a timer, a @code{FileSystemWatcher} or a Kestrel thread, posts an item and returns. A fiber takes the item with its own handlers, parameters and cancellation scope. An inbox always has a capacity, and a @code{WhenFull} policy says what a post does when the inbox is full. @code{inbox-call} is a request and a reply: the .NET caller gets a @code{Task}, and a fiber answers it.
|
||||
For more details, see @link["modules/std/inbox.html"]{@code{(std inbox)}}.
|
||||
|
||||
@subsection{std/interop}
|
||||
|
||||
Bridges for .NET APIs that want something a Bjolang function or value is not. A Bjolang function is a @code{Func} whose @code{void} return is the unit value; @code{as-delegate} and @code{as-delegate/type} wrap a function in another .NET delegate type such as @code{Action}, @code{EventHandler} or a library's custom delegate. @code{add-event-handler!} and @code{remove-event-handler!} subscribe a Bjolang function to a .NET object's event by name. @code{clr-default} produces .NET's @code{default(T)} (such as @code{null} for a reference type or a @code{Nullable<T>}) when a .NET call requires one.
|
||||
For more details, see @link["modules/std/interop.html"]{@code{(std interop)}}.
|
||||
|
||||
@subsection{std/os}
|
||||
|
||||
The operating system the program runs on: @code{windows?}, @code{linux?}, @code{macos?}, @code{freebsd?} and the others, @code{os-platform?} by name, and @code{windows-version-at-least?} and the other version checks, with the minor version, the build and the revision as keywords. Each is .NET's @code{OperatingSystem} method, called where it is written. .NET's core library is built for one system, so the method returns a constant there, and the JIT removes the branch that cannot run. A program is built once and chooses when it runs, and code for one system can be in a module of its own: a module that nothing calls does nothing.
|
||||
|
||||
It also has the facts about the machine and the process: @code{os-description}, @code{os-version}, @code{os-architecture}, @code{processor-count}, @code{available-memory}, @code{machine-name}, @code{user-name}, @code{process-id} and others. And the user's folders: @code{home-directory}, @code{config-directory}, @code{data-directory}, @code{cache-directory}, @code{documents-directory}, @code{desktop-directory} and @code{temp-directory}, which follow the XDG variables on Linux and each system's own place elsewhere, and @code{make-temp-directory} for a new directory that only its owner can enter.
|
||||
|
||||
And the signals, as union cases such as @code{Interrupt}, @code{Terminate} and @code{Hangup}. @code{with-signal-cancel} is a scope that the first of its signals cancels, so that a program cleans up on Ctrl-C or SIGTERM; a second signal ends the program at once. @code{on-signal} calls a function for each signal that comes, until the scope ends. @code{signal-subscribe} gives signals as values from the event @code{signal-recv}, and signals of one kind that wait are merged into one.
|
||||
For more details, see @link["modules/std/os.html"]{@code{(std os)}}.
|
||||
|
||||
@subsection{std/stream}
|
||||
|
||||
Loops over values that suspending work produces. A @code{Stream} is a driver, @code{(:for x s)}, whose producer is a bjoroutine that hands each value to the loop with @code{emit!}. Each loop over it starts the producer, which computes a value only when the loop asks for it, and stops it however the loop ends. @code{make-stream} makes one from a bjoroutine, and @code{{streaming expr clause ...}} from loop clauses. @code{in-chan} reads a channel that something else fills, until an event such as the producer's @code{promise-join} commits.
|
||||
For more details, see @link["modules/std/stream.html"]{@code{(std stream)}}.
|
||||
|
||||
@subsection{std/ports and std/net}
|
||||
|
||||
@code{(std ports)} reads and writes bytes on the prelude's ports. The byte reads @code{read-some-evt}, @code{read-bytes-evt} and @code{eof-evt} are CML events: a read that loses its @code{choose} takes nothing, so a read can race a timeout. @code{read-line} and @code{read-bytes} can be used on the same port. The module also drains ports into lists and vecs, streams them as a @code{Seq} or a channel, and has @code{byte-pipe}, a pair of ports with no file and no network, for tests. @code{(std net)} gives a TCP connection as a pair of these ports, so a protocol written for ports also runs over TCP. @code{accept-evt} is an event too: a branch that loses accepts nothing.
|
||||
@code{(std ports)} reads and writes bytes on the prelude's ports. The byte reads @code{read-some-evt}, @code{read-bytes-evt} and @code{eof-evt} are CML events: a read that loses its @code{choose} takes nothing, so a read can race a timeout. @code{read-line} and @code{read-bytes} can be used on the same port. The module also drains ports into lists and vecs, streams them as a @code{Seq} or, for a bjoroutine, as a @code{Stream} with @code{port->stream}, and has @code{byte-pipe}, a pair of ports with no file and no network, for tests. @code{(std net)} gives a TCP connection as a pair of these ports, so a protocol written for ports also runs over TCP. @code{accept-evt} is an event too: a branch that loses accepts nothing.
|
||||
For more details, see @link["modules/std/ports.html"]{@code{(std ports)}} and @link["modules/std/net.html"]{@code{(std net)}}.
|
||||
|
||||
@subsection{std/test and std/simpletest}
|
||||
|
|
@ -122,10 +189,25 @@ For more details, see @link["modules/std/syntax-match.html"]{@code{(std syntax-m
|
|||
|
||||
@subsection{text/bjodat}
|
||||
|
||||
bjodat is Bjolang's shapes read as data: no evaluation, no macro expansion, no environment. It is what a package manifest, a lockfile, or a config file is written in. You can parse text straight into a record using @code{bjodat-parse-<Name>}, which avoids intermediate trees and allocations.
|
||||
For more details, see @link["modules/text/bjodat.html"]{@code{(text bjodat)}}.
|
||||
bjodat is Bjolang's shapes read as data: no evaluation, no macro expansion, no environment. It is what a package manifest, a lockfile, or a config file is written in. You can parse text straight into a record using @code{bjodat-parse-<Name>}, which avoids intermediate trees and allocations. @code{(text bjodat-core)} is the machinery underneath: the @code{Bjodat} tree, with @code{parse-bjodat}, @code{bjodat-ref} and the writer, for data whose shape is not known until the program runs.
|
||||
For more details, see @link["modules/text/bjodat.html"]{@code{(text bjodat)}} and @link["modules/text/bjodat-core.html"]{@code{(text bjodat-core)}}.
|
||||
|
||||
@subsection{text/json}
|
||||
@subsection{text/json and text/json-codec}
|
||||
|
||||
The @code{text/json} module provides JSON parsing and generation capabilities. Like @code{bjodat}, it allows for working with structured data but using the standard JSON format, which is essential for web communication.
|
||||
For more details, see @code{prelude.org} and related standard library documentation.
|
||||
@code{(text json)} reads JSON, exactly as RFC 8259 has it, into a @code{Json}: a union with a case for each kind of value. @code{parse-json} reads a string and @code{read-json} a port. A document that is not JSON is an @code{Err} that says the line and column where it went wrong. A number without a fraction or an exponent is a @code{JsonInt}, and an object is a @code{(Map string Json)}, so the order of its keys is not kept. @code{(text json-codec)} reads a record straight from the tree and back: @code{def/json-type} declares a record and the instances of @code{->json} and @code{json->} for it, with defaults, optional fields and other names for the keys. An @code{Option} is @code{null} when it is @code{None}. There is no writer yet, so a @code{Json} cannot be written out as text.
|
||||
For more details, see @link["modules/text/json.html"]{@code{(text json)}} and @link["modules/text/json-codec.html"]{@code{(text json-codec)}}.
|
||||
|
||||
@subsection{text/csv and text/csv-codec}
|
||||
|
||||
@code{(text csv)} reads and writes CSV (RFC 4180), with configurable @code{#:separator}, @code{#:quote-char} and @code{#:strict?}. It reads in three layers: @code{csv-next!} pulls one row at a time, @code{csv-fold} and @code{csv-for-each} stream rows without keeping the document in memory, and @code{parse-csv} reads the whole input. Each row is an @code{(IArray string)}, and malformed input returns a @code{CsvError} with its line, row and field. @code{write-csv} and @code{csv->string} quote fields only when needed. @code{(text csv-codec)} maps rows to records and back: @code{def/csv-type} declares a record and its @code{CsvRecord} instance, matching columns by header name (or @code{#:csv} alias) or by position when @code{#:header? #f}, with @code{parse-csv-records}, @code{csv-for-each-record} and @code{write-csv-records}.
|
||||
For more details, see @link["modules/text/csv.html"]{@code{(text csv)}} and @link["modules/text/csv-codec.html"]{@code{(text csv-codec)}}.
|
||||
|
||||
@subsection{text/xml}
|
||||
|
||||
XML, in three modules over @code{System.Xml}. @code{(text xml)} is the tree: names, elements, texts, comments and processing instructions, built by @code{xml-element} and the others, and taken apart by views. @code{(text xml read)} reads XML in four layers: a stream of signals, a fold after SSAX, a tree of your own type, and @code{parse-xml}, which gives a @code{Document}. @code{xml-for-each} reads a large document one element at a time. The defaults are the safe ones: a document with a DOCTYPE is refused unless asked for, and nothing external is ever resolved. @code{(text xml write)} writes a node or a document to a port or a string. It chooses the namespace prefixes, and content that XML cannot hold is an @code{XmlWriteError} rather than an exception.
|
||||
For more details, see @link["modules/text/xml.html"]{@code{(text xml)}}, @link["modules/text/xml/read.html"]{@code{(text xml read)}} and @link["modules/text/xml/write.html"]{@code{(text xml write)}}.
|
||||
|
||||
@subsection{text/encodings}
|
||||
|
||||
Every character encoding .NET knows, as a value of the prelude's @code{Encoding}, to give to @code{string->bytes} and @code{bytes->string}, or to @code{reencode-input-port} and @code{reencode-output-port} from @code{(std ports)} for a port. There is one for each of the 139, named in lower case as .NET names them: @code{utf-16be}, @code{iso-8859-1}, @code{windows-1252}, @code{shift_jis}, @code{koi8-r} and the rest. .NET's little-endian @code{utf-16} and @code{utf-32} are @code{utf-16le} and @code{utf-32le} here. @code{encoding-named} finds one by name and @code{encoding-of-code-page} by number, both as an @code{Option}. No encoding writes or skips a byte order mark. Each encoding is made the first time it is used, so importing the module costs nothing.
|
||||
For more details, see @link["modules/text/encodings.html"]{@code{(text encodings)}}.
|
||||
|
|
|
|||
|
|
@ -1,54 +1,14 @@
|
|||
@section{Appendices}
|
||||
|
||||
@subsection{Coming from Scheme or ML}
|
||||
@subsection{Language inspiration}
|
||||
|
||||
Bjolang sits at the crossroads of two major functional programming lineages. From the Scheme and Lisp tradition, it draws its uniform S-expression syntax, prefix notation, code-as-data perspective, and hygienic macro system. From the ML family—specifically OCaml and F#—it inherits static Hindley-Milner type inference, algebraic data types, compile-time exhaustiveness checking, traits, and high-performance immutable data structures.
|
||||
Bjolang is firmly rooted in two large programming language families, and draws inspiration from both. I spent most of my life writing r6rs scheme. I think it is a beautiful language, and it is still often what I reach for to try out new things. The second is ML, mostly ocaml, with it's strong tradition of always managing to select the right abstractions. If you come from any of these languages you will feel at home in one way or the other. Some things I took from both -- like immutability -- will make adherents of both churches feel right at home and some things will feel weird.
|
||||
|
||||
Depending on which background you bring to Bjolang, parts of the language will feel like second nature while other parts will require shifting your mental habits.
|
||||
When deciding on API for bjolang I mostly asked myself "What would ocaml/scheme do?". With ocaml there is a rich set of libraries solving real world problems, so inspiration was easy to find, and from scheme I mostly had a look at racket (which is kind of r6.1rs).
|
||||
|
||||
@subsubsection{Coming from Scheme}
|
||||
A special nod goes to Alex Shinn of Chibi scheme. Both @code{(std fmt)}, @code{(std rx)} and @code{(std scan)} are heavily influenced by programs of his. In fact, the whole idea of the @code{loop} form comes from an earlier project of mine extending his foof-loop.
|
||||
|
||||
If you have written Scheme, Racket, or Common Lisp, the visual rhythm of Bjolang will feel immediately comfortable:
|
||||
|
||||
@read-list{
|
||||
- S-expression syntax and prefix notation: Expressions are nested parenthesized lists, and operators are ordinary functions called in prefix position: @code{(+ 1 2 (* 3 4))}.
|
||||
- Familiar control forms: Core branching and binding forms like @code{let}, @code{let*}, @code{cond}, @code{when}, @code{unless}, and @code{begin} behave as you expect.
|
||||
- First-class closures: Functions are first-class values created with @code{fun} (or @code{defun} at top level), capturing lexical scope, and passing into or returning from higher-order functions.
|
||||
- Persistent linked lists: The @code{List} type provides standard singly-linked functional lists with @code{Cons} and @code{Nil}, along with familiar combinators such as @code{list-head}, @code{list-tail}, @code{list-map}, and @code{list-filter}.
|
||||
- Hygienic macros: Bjolang features a compile-time syntactic macro system based on pattern matching with @code{syntax-match}, syntax quotation with @code{#'(...)}, and explicit identifier injection with @code{inject}.
|
||||
}
|
||||
|
||||
However, several fundamental differences will quickly become apparent:
|
||||
|
||||
@read-list{
|
||||
- Static typing and mandatory top-level signatures: Dynamic typing is absent. While types inside function bodies are inferred automatically using Hindley-Milner type inference, every top-level definition and exported value requires an explicit signature: @code{(: name type)}. Type errors are caught at compile time before any code runs.
|
||||
- No truthiness tricks or @code{#f}-as-nil: In Scheme, functions like @code{memq} or @code{assoc} return either a value or @code{#f} to signal absence, and @code{#f} is often treated as a general falsey sentinel. In Bjolang, absent values are strictly represented by the @code{(Option %a)} union (@code{Some} or @code{None}), and operations that may fail return @code{(Result %e %a)} (@code{Ok} or @code{Err}). Booleans (@code{#t} and @code{#f}) are strictly booleans; conditionals do not coerce non-boolean values.
|
||||
- Vectors and maps are persistent by default: In Scheme, vectors are mutable flat arrays. In Bjolang, @code{(Vec %a)} is an immutable Relaxed Radix Balanced (RRB) tree with efficient O(log n) random indexing, updates, and concatenation. Similarly, @code{(Map %k %v)} is an immutable Compressed Hash-Array Mapped Prefix-tree (CHAMP). In-place mutation is never the default: mutable state requires explicit declaration with @code{def/mutable} and modification with @code{set!}.
|
||||
- Structural pattern matching over @code{car}/@code{cdr}: Destructuring lists, records, and unions is done using the @code{match} construct rather than long chains of @code{car}, @code{cdr}, or @code{cadr}. The compiler checks pattern matches for exhaustiveness and warns or errors if any potential value is unaccounted for.
|
||||
- Concurrency without @code{call/cc}: Scheme systems often implement coroutines or thread libraries using first-class continuations (@code{call/cc}). Bjolang does not provide @code{call/cc}. Instead, it offers direct-style cooperative fibers (bjoroutines), typed channels, and Concurrent ML (CML) event combinators running on a dedicated fiber scheduler.
|
||||
}
|
||||
|
||||
@subsubsection{Coming from F# or OCaml}
|
||||
|
||||
If you come from F#, OCaml, or Haskell, the conceptual model of Bjolang's type system and runtime behavior will feel very natural:
|
||||
|
||||
@read-list{
|
||||
- Hindley-Milner type inference: Types within local expressions and function bodies are completely inferred. Polymorphic functions declare type variables with a leading percent sign, such as @code{%a} or @code{%elem}.
|
||||
- Algebraic data types: Data structures are modeled as sum types (@code{Union}) and product types (@code{Record} on the heap, or value-type @code{Struct} on the stack).
|
||||
- Exhaustive pattern matching: The compiler tracks which variants of a union or struct combination have been handled in a @code{match} or @code{def} binding, rejecting patterns that fail to cover every possible case.
|
||||
- Immutability by default: Data structures, record fields, and bindings are immutable unless explicitly declared mutable.
|
||||
- Traits and ad-hoc polymorphism: Bjolang's @code{def/trait} and @code{impl} system works much like Haskell typeclasses or Rust traits. Traits can define default method implementations, require super-traits, and specify associated types.
|
||||
- Direct-style concurrency: Concurrency is written in direct style without callback pyramids, closely resembling F#'s async computations or OCaml 5 effect handlers.
|
||||
}
|
||||
|
||||
The main shifts you will encounter coming from ML are:
|
||||
|
||||
@read-list{
|
||||
- Syntax and parentheses: There is no indentation-based syntax (like F#) or @code{let ... in} keyword framing (like OCaml). Everything is an S-expression with prefix notation. While this takes an afternoon to get used to, it makes code structure uniform and simplifies automated tooling.
|
||||
- First-class compile-time macros: Rather than relying on external preprocessors like OCaml's PPX or compiler plugins, Bjolang allows writing hygienic macros in the language itself using @code{def/macro}. These transformers run inside the compiler process during the expansion phase.
|
||||
- Concurrent ML events instead of raw tasks: Rather than manipulating raw asynchronous tasks or promises directly, Bjolang builds upon Concurrent ML. The primitive unit of asynchronous composition is the @code{(Event %a)}. Events can be combined with @code{choose}, wrapped with transformations via @code{wrap}, and selectively synchronized using @code{sync}.
|
||||
- Automatic colour twins: In many typed asynchronous languages, asynchronous functions have distinct types (@code{Task<'T>} or @code{Async<'T>}) that cannot be passed to standard higher-order functions like @code{List.map} without creating asynchronous duplicates (@code{List.mapAsync}). Bjolang solves this "function colouring problem" at the compiler level: higher-order functions declaring @code{-?->} parameters automatically generate both synchronous and suspending twins, allowing the exact same @code{list-map} to be used whether your callback performs I/O or pure computation.
|
||||
}
|
||||
The concurrency story is that of ConcurrentML. A language almost as old as me, that has lived on in various smaller projects. It came to my attention through Andy Wingo, who in his turn got it from the sages of Racket. There are various resources online about it, but I would really recommend watching Andy's speeches about it. There is also a talk circulating online from Mike Sperber talking about it, which can probably be found on the large streaming site.
|
||||
|
||||
@subsection{Reading compiler errors}
|
||||
|
||||
|
|
@ -67,12 +27,12 @@ When compiled, the frontend rejects this with:
|
|||
Type Error: Function 'greet' requires a type signature (: greet ...) at hello.bjo:1:1
|
||||
}|
|
||||
|
||||
@strong{Why it happens:} Unlike local helper functions defined inside another function, every top-level definition in a module must carry an explicit type signature. The compiler requires this so that module interfaces are self-documenting and can be emitted into the compiled assembly's public metadata without requiring whole-program inference across files. The only exception is @code{main}, which has a fixed signature known to the compiler.
|
||||
@strong{Why it happens:} Unlike local helper functions defined inside another function, every top-level definition in a module must carry an explicit type signature. The compiler requires this so that module interfaces are self-documenting and can be emitted into the compiled assembly's public metadata without requiring whole-program inference across files. The only exception is @code{main}: the compiler knows what it takes, the arguments as a @code{(Vec string)}, and what it returns is the exit code when it is an int.
|
||||
|
||||
@strong{How to fix it:} Add an explicit signature right before the definition:
|
||||
|
||||
@codeblock[#:lang "bjolang"]|{
|
||||
(: greet (-> string unit))
|
||||
(: greet (-> string void))
|
||||
(defun (greet name)
|
||||
(println (str "Hello, " name)))
|
||||
}|
|
||||
|
|
@ -414,3 +374,17 @@ Key editing features and keybindings include:
|
|||
- @code{C-c C-o}: Follow the reference at point, opening the target URL or jumping directly to an included file.
|
||||
- Document navigation: Seamless integration with @code{outline-minor-mode} and @code{imenu} allows folding sections and navigating complex documents through hierarchical headings.
|
||||
}
|
||||
|
||||
@subsection{Why it is a sad world on dotnet}
|
||||
|
||||
The reason bjolang runs on dotnet is mostly because of inertia. I had a lot of code already written for c#, and reimplementing RRB trees or CHAMPs in ocaml is nothing I felt like doing. Running on dotnet comes with tradeoffs, most notably function colouring. Had I gone with ocaml5, I would have got effect handlers, which means delimited control, which means everything can potentially be a bjoroutine. Now I have async, which means colouring and compiling functions in two ways and sad faces all the way down.
|
||||
|
||||
The longer I have come with bjolang, the more I have started looking sideways at ocaml. When it comes to selecting abstractions, ocaml and racket are somehow almost always spot on, which means my main design guideline is "when in doubt, look at ocaml/racket/(guile)". A lot of the things that were not implemented in bjolang are things that simply were too expensive on dotnet, but more or less free on ocaml.
|
||||
|
||||
Most of it is delimited control, but having the world's best STM and full effect handlers would make my life a breeze.
|
||||
|
||||
@subsubsection{So... when will you switch?}
|
||||
|
||||
Probably never. Interop is too nice to have. Just being able to Nuget a nice markdown parser and write some glue is just too damn nice. I did some playing with ocaml, and there are some things I really do not like. Minor gc collections stop all domains. Boxed generics.
|
||||
|
||||
But the effect handlers, man...
|
||||
|
|
|
|||
3
index.sz
3
index.sz
|
|
@ -11,7 +11,6 @@ types, traits, hygienic macros and bjoroutines, that compiles to C#.
|
|||
library module, made from the documentation the module was compiled with.
|
||||
@itemlist{
|
||||
@item{@link["modules/std/"]{@code{std}}: the standard library.}
|
||||
@item{@link["modules/text/"]{@code{text}}: data formats: bjodat, JSON
|
||||
and XML.}
|
||||
@item{@link["modules/text/"]{@code{text}}: data formats and encodings: bjodat, CSV, JSON and XML.}
|
||||
}}
|
||||
}
|
||||
|
|
|
|||
3
modules/std/array.sz
Normal file
3
modules/std/array.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std array)"))
|
||||
|
||||
@generate-docs[#:module "std array"]
|
||||
3
modules/std/combine.sz
Normal file
3
modules/std/combine.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std combine)"))
|
||||
|
||||
@generate-docs[#:module "std combine"]
|
||||
3
modules/std/crypto/hash.sz
Normal file
3
modules/std/crypto/hash.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std crypto hash)"))
|
||||
|
||||
@generate-docs[#:module "std crypto hash"]
|
||||
2
modules/std/crypto/index.sz
Normal file
2
modules/std/crypto/index.sz
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
(meta (title "(std crypto)")
|
||||
(sort title))
|
||||
3
modules/std/interop.sz
Normal file
3
modules/std/interop.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std interop)"))
|
||||
|
||||
@generate-docs[#:module "std interop"]
|
||||
3
modules/std/os.sz
Normal file
3
modules/std/os.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std os)"))
|
||||
|
||||
@generate-docs[#:module "std os"]
|
||||
3
modules/std/parallel.sz
Normal file
3
modules/std/parallel.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std parallel)"))
|
||||
|
||||
@generate-docs[#:module "std parallel"]
|
||||
3
modules/std/priority-queue.sz
Normal file
3
modules/std/priority-queue.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std priority-queue)"))
|
||||
|
||||
@generate-docs[#:module "std priority-queue"]
|
||||
3
modules/std/rational.sz
Normal file
3
modules/std/rational.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std rational)"))
|
||||
|
||||
@generate-docs[#:module "std rational"]
|
||||
3
modules/std/scan.sz
Normal file
3
modules/std/scan.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std scan)"))
|
||||
|
||||
@generate-docs[#:module "std scan"]
|
||||
3
modules/std/simd.sz
Normal file
3
modules/std/simd.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std simd)"))
|
||||
|
||||
@generate-docs[#:module "std simd"]
|
||||
3
modules/std/stream.sz
Normal file
3
modules/std/stream.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std stream)"))
|
||||
|
||||
@generate-docs[#:module "std stream"]
|
||||
3
modules/std/text.sz
Normal file
3
modules/std/text.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std text)"))
|
||||
|
||||
@generate-docs[#:module "std text"]
|
||||
3
modules/std/unicode/grapheme.sz
Normal file
3
modules/std/unicode/grapheme.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std unicode grapheme)"))
|
||||
|
||||
@generate-docs[#:module "std unicode grapheme"]
|
||||
2
modules/std/unicode/index.sz
Normal file
2
modules/std/unicode/index.sz
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
(meta (title "(std unicode)")
|
||||
(sort title))
|
||||
3
modules/std/units.sz
Normal file
3
modules/std/units.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std units)"))
|
||||
|
||||
@generate-docs[#:module "std units"]
|
||||
3
modules/std/uuid.sz
Normal file
3
modules/std/uuid.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(std uuid)"))
|
||||
|
||||
@generate-docs[#:module "std uuid"]
|
||||
3
modules/text/csv-codec.sz
Normal file
3
modules/text/csv-codec.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(text csv-codec)"))
|
||||
|
||||
@generate-docs[#:module "text csv-codec"]
|
||||
3
modules/text/csv.sz
Normal file
3
modules/text/csv.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(text csv)"))
|
||||
|
||||
@generate-docs[#:module "text csv"]
|
||||
3
modules/text/encodings.sz
Normal file
3
modules/text/encodings.sz
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
(meta (title "(text encodings)"))
|
||||
|
||||
@generate-docs[#:module "text encodings"]
|
||||
Loading…
Add table
Add a link
Reference in a new issue