Compare commits

..

6 Commits

Author SHA1 Message Date
Scott Richmond
2ad939b48b repl cruft 2024-06-15 21:53:40 -04:00
Scott Richmond
e899bc96f0 updated doc 2024-06-15 21:53:09 -04:00
Scott Richmond
bce3f9d7b0 properly show sets 2024-06-15 21:52:50 -04:00
Scott Richmond
6022895fa8 improve formatting and add new functions to topics 2024-06-15 21:52:19 -04:00
Scott Richmond
07c6d23587 bugfixes and improvements 2024-06-15 21:51:56 -04:00
Scott Richmond
d64467ef6d accurately describe current Ludus 2024-06-15 21:50:46 -04:00
6 changed files with 323 additions and 382 deletions

View File

@ -27,10 +27,28 @@ Ludus keywords begin with a colon and a letter, e.g. `:keyword`. Types are repre
Keywords must begin with an ASCII upper- or lower-case letter, and can then include any letter character, as well as `_`, `/`, `!`, `?`, and `*`. Keywords must begin with an ASCII upper- or lower-case letter, and can then include any letter character, as well as `_`, `/`, `!`, `?`, and `*`.
## Strings ## Strings
Ludus strings are dependent on the host platform. Given that Ludus either runs in Javascript or the JVM, strings are UTF-16 strings. Eventually, Ludus will use UTF-8 strings. Strings are much more complicated than you think. Strings are emphatically not a collection type. Ludus strings are UTF-8 strings, and only use double quotes. Strings may be multiline. For example, this is a string: `"foo"`. So is this:
```
"foo
bar baz"
```
Strings use backslashes for escapes, including `\n` for newline, `\t` for tab, `\"` for a double quote, and `\{` for an open curly brace (see below on interpolation).
Strings' type is `:string`. Strings' type is `:string`.
### String interpolation
Strings may also insert a string representation of any Ludus value that is bound to a name, by inserting that name in curly braces, e.g.
```
let foo = :foo
let bar = 42
let baz = [1, 2, 3]
"{foo} {bar} {baz}" &=> ":foo 42 1, 2, 3"
```
Interpolations may _not_ be arbitrary expressions: only bound names may be used in interpolations.
## Collections ## Collections
Ludus has a few different types of collections, in increasing order of complexity: tuples, lists, sets, dicts, and namespaces. Ludus has a few different types of collections, in increasing order of complexity: tuples, lists, sets, dicts, and namespaces.
@ -41,7 +59,7 @@ In all collection literals, members are written with a separator between them. O
Tuples are fully-immutable, ordered collections of any kinds of values, delimited by parentheses, e.g. `(1, :a, "foo")`. At current, they have no length limit (although they eventually will). Unlike in some languages, tuples can be empty or contain a single element: `()` and `(:foo)` are both just fine. Tuples largely cannot be manipulated functionally; they must be written as literals and unpacked using pattern matching. They can, however, be converted to lists, either through pattern matching or the `list` function. Their type is `:tuple`. Tuples are fully-immutable, ordered collections of any kinds of values, delimited by parentheses, e.g. `(1, :a, "foo")`. At current, they have no length limit (although they eventually will). Unlike in some languages, tuples can be empty or contain a single element: `()` and `(:foo)` are both just fine. Tuples largely cannot be manipulated functionally; they must be written as literals and unpacked using pattern matching. They can, however, be converted to lists, either through pattern matching or the `list` function. Their type is `:tuple`.
### Lists ### Lists
Lists are persistent and immutable ordered collections of any kinds of values, delimited by square braces, e.g. `[1, :a, "foo"]`. They are currently implemented using Clojure's persistent vectors. Their type is `:list`. Lists are persistent and immutable ordered collections of any kinds of values, delimited by square braces, e.g. `[1, :a, "foo"]`. Their type is `:list`.
Lists may be combined using splats, written with ellipses, e.g., `[...foo, ...bar]`. Lists may be combined using splats, written with ellipses, e.g., `[...foo, ...bar]`.
@ -51,13 +69,13 @@ Sets are persistent and immutable unordered collections of any kinds of values,
### Dictionaries, or dicts ### Dictionaries, or dicts
Dicts are persistent and immutable associative collections of any kinds of values. Dicts use keywords as keys (and cannot use any other kind of Ludus value as a key, not even strings), but can store any values. Dict literals are written as keyword-value pairs: `#{:a 1, :b false}`. Single words may be used as a shorthand for a key-value pair. Accessing a key that holds no value returns `nil`. Their type is `:dict`. Dicts are persistent and immutable associative collections of any kinds of values. Dicts use keywords as keys (and cannot use any other kind of Ludus value as a key, not even strings), but can store any values. Dict literals are written as keyword-value pairs: `#{:a 1, :b false}`. Single words may be used as a shorthand for a key-value pair. Accessing a key that holds no value returns `nil`. Their type is `:dict`.
### Namespaces ### Packages
Namespaces are immutable collections of bindings. They may only be described at the top level of a script. Accessing a key that has no value on a namepsace results in a panic. Their type is `:ns`. Packages are immutable collections of bindings. They may only be described at the top level of a script, and their names must begin with a capital letter. Accessing a key that has no value on a package results in a panic. They may not be accessed using functions, only direct keyword access. Their type is `:pkg`.
They are written with the form `ns`, then a word that will be bound as their name, and then an associative structure (pairs or word shorthands), delimited by `{}`, e.g.: They are written with the form `pkg`, then a package name, beginning with a capital letter, that will be bound as their name, and then an associative structure (pairs or word shorthands), delimited by `{}`, e.g.:
``` ```
ns foo { pkg Foo {
:bar "bar" :bar "bar"
:baz 42 :baz 42
quux quux
@ -67,26 +85,26 @@ ns foo {
### Working with collections ### Working with collections
Ludus names are bound permanently and immutably. How do you add something to a list or a dict? How do you get things out of them? Ludus names are bound permanently and immutably. How do you add something to a list or a dict? How do you get things out of them?
Ludus provides functions that allow working with persistent collections. They're detailed in [the Prelude](/prelude.md). That said, all functions that modify collections take a collection and produce the modified collection _as a return value_, without changing the original collection. E.g., `append ([1, 2, 3], 4)` will produce `[1, 2, 3, 4]`. (For dicts, the equivalent is `assoc`.) Ludus provides functions that allow working with persistent collections. They're detailed in [the Prelude](/prelude.md). That said, all functions that modify collections take a collection and produce the modified collection _as a return value_, without changing the original collection. E.g., `append ([1, 2, 3], 4)` will produce `[1, 2, 3, 4]`, but the original list is unchanged. (For dicts, the equivalent is `assoc`.)
## Expressions ## Expressions
Ludus is an expression-based language: all forms in the language are expressions and return values, except `panic!`. That said, not all expressions may be used everywhere. Ludus is an expression-based language: all forms in the language are expressions and return values, except `panic!`. That said, not all expressions may be used everywhere.
### Toplevel expressions ### Toplevel expressions
Some expressions may only be used in the "top level" of a script. Because they are the toplevel, they are assured to be statically knowable. These include: `ns`, `use`, `import`, and `test`. Some expressions may only be used in the "top level" of a script. Because they are the toplevel, they are assured to be statically knowable. These include: `pkg`, `ns`, `use`, `import`, and `test`. (NB: not all of these are yet implemented.)
### Non-binding expressions ### Non-binding expressions
Some forms may take any expression that does _not_ [bind a name](#Words-and-bindings), for example, any entry in a collection, or the right-hand side of a `let` binding. This is because binding a name in some positions is ambiguous, or nonsensical, or leads to unwarranted complications. Some forms may take any expression that does _not_ [bind a name](#Words-and-bindings), for example, any entry in a collection, or the right-hand side of a `let` binding. This is because binding a name in some positions is ambiguous, or nonsensical, or leads to unwarranted complications.
### Simple expressions ### Simple expressions
Many complex forms will only accept "simple" expressions. Formally, simple expressions are either literal (atomic, string, or collection literals) or synthetic expressions. They are expressions which do not take sub-expressions: no `if`, `when`, `match`, etc. (`do` expressions are currently not simple, but that may be revised.) Many compound forms will only accept "simple" expressions. Formally, simple expressions are either literal (atomic, string, or collection literals) or synthetic expressions. They are expressions which do not take sub-expressions: no `if`, `when`, `match`, etc. (`do` expressions are currently not simple, but that may be revised.)
## Words and bindings ## Words and bindings
Ludus uses _words_ to bind values to names. Words must start with a lower case ASCII letter, and can subsequently include any letter character (modulo backing character encoding), as well as , `_`, `/`, `?`, `!`, and `*`. Ludus uses _words_ to bind values to names. Words must start with a lower case ASCII letter, and can subsequently include any letter character (modulo backing character encoding), as well as , `_`, `/`, `?`, `!`, and `*`.
Ludus binds values to names immutably and permanently: no name in the same scope may ever be re-bound to a different value. (Although see [refs](#references-and-state), below. Ludus binds values to names immutably and permanently: no name in the same scope may ever be re-bound to a different value. (Although see [refs](#references-and-state), below.
Attempting to use an unbound name (a word that has not had a value bound to it) will result in a panic. Attempting to use an unbound name (a word that has not had a value bound to it) will result in a validation error, and the script will not run.
### `let` bindings: a very short introduction ### `let` bindings: a very short introduction
Ludus's basic binding form is `let`: Ludus's basic binding form is `let`:
@ -94,7 +112,7 @@ Ludus's basic binding form is `let`:
``` ```
let foo = :bar & `foo` is now bound to `bar` for the rest of the scope. let foo = :bar & `foo` is now bound to `bar` for the rest of the scope.
let foo = :baz & panic! let foo = :baz & Validation error: name foo was bound in line 1
``` ```
`let` bindings are more complex; we will return to these below. `let` bindings are more complex; we will return to these below.
@ -106,10 +124,10 @@ Ludus makes extensive use of pattern-matching. Patterns do two jobs at once: the
The simplest pattern is the placeholder: it matches against anything, and does not bind a name. It is written as a single underscore: `_`, e.g., `let _ = :foo`. The simplest pattern is the placeholder: it matches against anything, and does not bind a name. It is written as a single underscore: `_`, e.g., `let _ = :foo`.
#### Ignored names #### Ignored names
If you wish to be a bit more explict than using a placeholder, you can use an ignored name, which is a name that starts with an underscore: `_foo`. This is not bound, is not a valid name, and can be used however much you wish, even multiple times in the same pattern. It's a placeholder, plus a reader-facing description. If you wish to be a bit more explict than using a placeholder, you can use an ignored name, which is a name that starts with an underscore: `_foo`. This is not bound, is not a valid name, and can be used however much you wish, even multiple times in the same pattern. It is, in fact, a placeholder, plus a reader-facing description.
### Literal patterns ### Literal patterns
Patterns can be literal atomic values or strings: `0`, `false`, `nil`, `"foo"`, etc. That means you can write `let 0 = 0` or `let :foo = :foo`, and everything will be jsut fine. Patterns can be literal atomic values or strings: `0`, `false`, `nil`, `:foo`, etc. That means you can write `let 0 = 0` or `let :foo = :foo`, and, while nothing will happen, everything will be just fine.
Literals match against, well, literal values: if the pattern and the value are the same, they match! If not, they don't match. Literals match against, well, literal values: if the pattern and the value are the same, they match! If not, they don't match.
@ -121,6 +139,24 @@ Word patterns match against any value, and bind that value to the word as a name
#### Typed patterns #### Typed patterns
Word patterns can, optionally, take a type, using the `as` reserved word, and the keyword representing the desired type: `let foo as :number = 42`. Word patterns can, optionally, take a type, using the `as` reserved word, and the keyword representing the desired type: `let foo as :number = 42`.
### String patterns
Ludus has a simple but powerful form of string pattern matching that mirrors string interpolation. Any word inside curly braces in a string will match against a substring of a string passed into a pattern.
```
let i_am = "I am the walrus"
let "I {verb} the {noun}" = i_am
(verb, noun) &=> ("am", "walrus")
```
Note that such names may well be bound to empty strings: a match does not guarantee that there will be anything in the string. This is particularly relevant at the beginning and end of string patterns:
```
let we_are = "We are the eggmen"
let "{first}We {what}" = we_are
(first, what) &=> ("", "are the eggmen")
```
### Collection patterns ### Collection patterns
Tuples, lists, and dicts can be destructured using patterns. They are written nearly identically to their literal counterparts. Collection patterns are composed of any number of simpler patterns or other collection patterns. They bind any names nested in them, match literals in them, etc. Tuples, lists, and dicts can be destructured using patterns. They are written nearly identically to their literal counterparts. Collection patterns are composed of any number of simpler patterns or other collection patterns. They bind any names nested in them, match literals in them, etc.
@ -141,11 +177,15 @@ let () = () & empty tuples are also patterns
#### List patterns #### List patterns
List patterns are identical to tuple patterns, but they are written using square braces. They also match against a specific number of members, and may take a splat in the last position, e.g. `let [first, ...rest] = [1, 2, 3]`. List patterns are identical to tuple patterns, but they are written using square braces. They also match against a specific number of members, and may take a splat in the last position, e.g. `let [first, ...rest] = [1, 2, 3]`.
Note that list patterns, like tuple patterns, match on explicit length. That means that if you are matching only the first items of a list, you must explicitly include a splat pattern, e.g. `let [first, second, ...] = [1, 2, 3, 4]`.
#### Dict patterns #### Dict patterns
Dict patterns are written either with shorthand words, or keyword-pattern pairs. Consider: `let #{:a foo, :b 12, c} = #{:a 1, :b 12, :c 4}`. `foo` is now 1; `b` is now 12, `c` is now 4. If a dict does not hold a value at a particular key, there is no match. Dict patterns are written either with shorthand words, or keyword-pattern pairs. Consider: `let #{:a foo, :b 12, c} = #{:a 1, :b 12, :c 4}`. `foo` is now 1; `b` is now 12, `c` is now 4. If a dict does not hold a value at a particular key, there is no match.
Dict patterns may also use a splat as their last member: `let #{:a 1, ...b} = #{:a 1, :b 2, :c 3}` will bind `b` to `#{:b 2, :c 3}`. Dict patterns may also use a splat as their last member: `let #{:a 1, ...b} = #{:a 1, :b 2, :c 3}` will bind `b` to `#{:b 2, :c 3}`.
Like tuple and list patterns, dict patterns without a splat at the end match only on exact equivalence on all keys.
## `let` bindings ## `let` bindings
`let` bindings are the basic form of matching and binding in Ludus. It is written `let {pattern} = {non-binding expression}`. The pattern can be arbitrarily complex. If the left-hand side of a `let` binding does not match, Ludus will raise a panic, halting evaluation of the script. `let` bindings are the basic form of matching and binding in Ludus. It is written `let {pattern} = {non-binding expression}`. The pattern can be arbitrarily complex. If the left-hand side of a `let` binding does not match, Ludus will raise a panic, halting evaluation of the script.
@ -162,7 +202,7 @@ let first = {
add (outer, inner) add (outer, inner)
} & first is now bound to 65 } & first is now bound to 65
inner & panic! unbound name inner inner & Validation error! unbound name inner
``` ```
@ -182,37 +222,28 @@ let y = {
``` ```
## Conditional forms ## Conditional forms
Ludus has a robust set of conditionoal forms, all of which are expressions and resolve to a single value. Ludus has a robust set of conditional forms, all of which are expressions and resolve to a single value.
### `if` ### `if`
`if` evaluates a condition; if the result of the condition is truthy, it evaluates is `then` branch; if the condition is falsy, it evaluates its `else` branch. Both branches must always be present. Newlines may come before `then` and `else`. `if` evaluates a condition; if the result of the condition is truthy, it evaluates is `then` branch; if the condition is falsy, it evaluates its `else` branch. Both branches must always be present. Newlines may come before `then` and `else`.
`if {simple expression} then {non-binding expression} else {non-binding expression}` `if {simple expression} then {non-binding expression} else {non-binding expression}`
#### `if let`
There is one exception to the above: a single `let` form can be used as the condition. In that case, if the `let` binding is successful--the pattern matches--the `then` branch is evaluated with any resulting bindings. If the pattern does not match, in place of a panic, the `else` branch is evaluated. Note that if the right-hand value of the `let` expression is falsy, the `else` branch will also be evaluated.
```
if let (:ok, value) = might_fail ()
then do_something_with (value)
else recover
```
### `when` ### `when`
`when` is like Lisp's `cond`: it takes a series of clauses, separated by semicolons or newlines, delimited by curly braces. Clauses are written `lhs -> rhs`. `when` expressions are extremely useful for avoiding nested `if`s. `when` is like Lisp's `cond`: it takes a series of clauses, separated by semicolons or newlines, delimited by curly braces. Clauses are written `lhs -> rhs`. `when` expressions are extremely useful for avoiding nested `if`s.
The left hand of a clause is a simple expression; the right hand of a clause is any expression. When the left hand is truthy, the right hand is evaluated, and the result of that evaluation is returned; no further clauses are evaluated. If no clause has a truthy left-hand value, then a panic is raised. `else` and `_` are valid left-hand expressions, which are always truthy in this context. The left hand of a clause is a simple expression; the right hand of a clause is any expression. When the left hand is truthy, the right hand is evaluated, and the result of that evaluation is returned; no further clauses are evaluated. If no clause has a truthy left-hand value, then a panic is raised. In the example below, not the use of literal `true` as an always-matching clause.
``` ```
when { when {
maybe () -> :something maybe () -> :something
mabye_not () -> :something_else mabye_not () -> :something_else
else -> :always true -> :always
} }
``` ```
### `match` ### `match`
A `match` form is the most powerful conditional form in Ludus (for now). It consists of a test expression, and a series of clauses. The test expression must be a simple expression, followed by `with`, and then a series of clauses separated by a semicolon or newline, delimited by curly braces. A `match` form is the most powerful conditional form in Ludus. It consists of a test expression, and a series of clauses. The test expression must be a simple expression, followed by `with`, and then a series of clauses separated by a semicolon or newline, delimited by curly braces.
``` ```
match may_fail () with { match may_fail () with {
@ -223,9 +254,9 @@ match may_fail () with {
The left hand of a match clause is a pattern; the right hand is an expression: `pattern -> expression`. If the pattern matches the test expression of a clause, the expression is evaluated with any bindings from the pattern, and `match` form evaluates to the result of that expression. The left hand of a match clause is a pattern; the right hand is an expression: `pattern -> expression`. If the pattern matches the test expression of a clause, the expression is evaluated with any bindings from the pattern, and `match` form evaluates to the result of that expression.
If a test expression does not match against any clause's pattern, a panic is raised. As with `when` expressions, `_` and `else` always match. If a test expression does not match against any clause's pattern, a panic is raised.
Ludus does not attempt to do any exhaustiveness checking on match forms. Ludus does not attempt to do any exhaustiveness checking on match forms; match errors are always runtime errors.
## Functions ## Functions
Ludus is an emphatically functional language. Almost everything in Ludus is accomplished by applying functions to values, or calling functions with arguments. (These are precise synonyms.) Ludus is an emphatically functional language. Almost everything in Ludus is accomplished by applying functions to values, or calling functions with arguments. (These are precise synonyms.)
@ -260,6 +291,23 @@ fn some {
### Closures ### Closures
Functions in Ludus are closures: function bodies have access not only to their specific scope, but any enclosing scope. Note that function bodies may have access to names bound after them in their scope, so long as the function is _called_ after any names it accesses are bound. Functions in Ludus are closures: function bodies have access not only to their specific scope, but any enclosing scope. Note that function bodies may have access to names bound after them in their scope, so long as the function is _called_ after any names it accesses are bound.
### Mutual recursion and forward declaration
If you try the following, you'll get a validation error:
```
fn stupid_odd? {
(0) -> false
(x) -> supid_even? (dec (x)) & Validation error: unbound name
}
fn stupid_even? {
(0) -> true
(x) -> stupid_odd? (dec (x))
}
```
To allow for mutual recursion, Ludus allows forward declarations, which are written `fn name` without any clauses. In the example above, we would simply put `fn stupid_even?` before we define `stupid_odd?`. If you declare a function without defining it, however, Ludus will raise a validation error.
### The Prelude ### The Prelude
The Prelude is a substantial set of functions that is available in any given Ludus script. (It is, itself, just a Ludus file that has special access to host functions.) Because of that, a large number of functions are always available. The prelude documentation is [here](/prelude.md). The Prelude is a substantial set of functions that is available in any given Ludus script. (It is, itself, just a Ludus file that has special access to host functions.) Because of that, a large number of functions are always available. The prelude documentation is [here](/prelude.md).
@ -274,11 +322,11 @@ Because of "partial application," Ludus has a concept of an "argument tuple" (wh
In place of nesting function calls inside other function calls, Ludus allows for a more streamlined version of function application: the `do` form or function pipeline. `do` is followed by an initial expression. `do` expressions use `>` as an operator: whatever is on the left hand side of the `>` is passed in as a single argument to whatever is on its right hand side. For example: In place of nesting function calls inside other function calls, Ludus allows for a more streamlined version of function application: the `do` form or function pipeline. `do` is followed by an initial expression. `do` expressions use `>` as an operator: whatever is on the left hand side of the `>` is passed in as a single argument to whatever is on its right hand side. For example:
``` ```
let silly_result = do 23 let silly_result = do 23 >
> mult (_, 2) > add (1, _) mult (_, 2) > add (1, _) >
> sub (_, 2) > div (_, 9) & silly_result is 5 sub (_, 2) > div (_, 9) & silly_result is 5
``` ```
Newlines may appear before any instance of `>` in a `do` expression. Newlines may appear after any instance of `>` in a `do` expression. That does, however, mean that you must be careful not to accidentally include any trailing `>`s.
### Called keywords ### Called keywords
Keywords may be called as functions, in which case they extract the value stored at that key in the value passed in: Keywords may be called as functions, in which case they extract the value stored at that key in the value passed in:
@ -290,8 +338,16 @@ let bar = :a (foo) & `bar` is now 1
Called keywords can be used in pipelines. Called keywords can be used in pipelines.
In addition, keywords may be called when they are bound to names:
```
let foo = #{:a 1, :b 2}
let bar = :a
bar (foo) & => 1
```
## Synthetic expressions ## Synthetic expressions
Synthetic expressions are valid combinations of words, keywords, and argument tuples which allow for calling functions and extracting values from associative collections. The root--first term--of a synthetic expression must be a word or a keyword; subsequent terms must be either argument tuples or keywords. Synthetic expressions are valid combinations of words, keywords, package names, and argument tuples which allow for calling functions and extracting values from associative collections. The root--first term--of a synthetic expression must be a word or a keyword; subsequent terms must be either argument tuples or keywords.
``` ```
let foo = #{:a 1, :b #{:c "bar" :d "baz"}} let foo = #{:a 1, :b #{:c "bar" :d "baz"}}
@ -303,7 +359,7 @@ let baz = :b (foo) :d & `baz` is now "baz"
``` ```
## Looping forms ## Looping forms
Ludus will have optimized tail calls--the most straightforward way to accomplish repeating behaviour is function recursion. There are two additional looping forms, `repeat` and `loop`. Ludus has optimized tail calls--the most straightforward way to accomplish repeating behaviour is function recursion. There are two additional looping forms, `repeat` and `loop`.
### `repeat` ### `repeat`
`repeat` is a help to learners, and is useful for executing side effects multiple times. It is written `repeat {number|word} { {exprs} }`. From turtle graphics: `repeat` is a help to learners, and is useful for executing side effects multiple times. It is written `repeat {number|word} { {exprs} }`. From turtle graphics:
@ -316,8 +372,8 @@ repeat 4 {
``` ```
Note that `repeat` does two interesting things: Note that `repeat` does two interesting things:
1. It never returns a value other than `nil`. If it's in the block, it disappears. 1. It never returns a value other than `nil`. If it's in the block, it disappears. This is a unique (and frankly, undesirable) property in Ludus.
2. Unlike everything else in Ludus, it requires a block. You cannot write `repeat 4 forward! (100)`. (But: watch this space.) 2. Unlike everything else in Ludus, repeate _requires_ a block, and not simply an expression. You cannot write `repeat 4 forward! (100)`.
### `loop`/`recur` ### `loop`/`recur`
`loop` and `recur` are largely identical to recursive functions for repetition, but use a special form to allow an anonymous construction and a few guard rails. `loop` and `recur` are largely identical to recursive functions for repetition, but use a special form to allow an anonymous construction and a few guard rails.
@ -332,7 +388,9 @@ loop (xs, 0) with {
} &=> 10 } &=> 10
``` ```
`recur` is the recursive call. It must be in tail position--`recur` must be the root of a synthetic expression, in return position. (At present, this is not checked. It will be statically verified, eventually.) `recur` is the recursive call. It must be in tail position--`recur` must be the root of a synthetic expression, in return position. If `recur` is not in tail position, a validation error will be raised.
In addition, `recur` calls must have the same number of arguments as the original tuple passed to `loop`. While Ludus will allow you to write clauses in `loop` forms with a different arity than the original tuple, those will never match.
`recur` calls return to the nearest `loop`. Nested `loop`s are probably a bad idea and should be avoided when possible. `recur` calls return to the nearest `loop`. Nested `loop`s are probably a bad idea and should be avoided when possible.
@ -342,14 +400,18 @@ The "toplevel" of a script are the expressions that are not embedded in other ex
### `import` ### `import`
`import` allows for the evaluation of other Ludus scripts: `import "path/to/file" as name`. `import` just evaluates that file, and then binds a name to the result of evaluating that script. This, right now, is quite basic: circular imports are currently allowed but will lead to endless recursion; results are not cached, so each `import` in a chain re-evaluates the file; and so on. `import` allows for the evaluation of other Ludus scripts: `import "path/to/file" as name`. `import` just evaluates that file, and then binds a name to the result of evaluating that script. This, right now, is quite basic: circular imports are currently allowed but will lead to endless recursion; results are not cached, so each `import` in a chain re-evaluates the file; and so on.
Status: not yet implemented.
### `use` ### `use`
`use` loads the contents of a namespace into a script's context. To ensure that this is statically checkable, this must be at the toplevel. `use` loads the contents of a namespace into a script's context. To ensure that this is statically checkable, this must be at the toplevel.
### `ns` Status: not yet implemented
Namespaces, `ns`es, may only be described at the toplevel of a script. This is to ensure they can be statically evaluatable.
### `pkg`
Packages, `pkg`es, may only be described at the toplevel of a script. This is to ensure they can be statically evaluatable.
### `test` ### `test`
A `test` expression (currently not working!--it will blow up your script, although it parses properly) is a way of ensuring things behave the way you want them to. Run the script in test mode (how?--that doesn't exist yet), and these are evaluated. If the expression under `test` returns a truthy value, you're all good! If the expression under `test` returns a falsy value or raises a panic, then Ludus will report which test(s) failed. A `test` expression is a way of ensuring things behave the way you want them to. Run the script in test mode, and these are evaluated. If the expression under `test` returns a truthy value, you're all good! If the expression under `test` returns a falsy value or raises a panic, then Ludus will report which test(s) failed.
``` ```
test "something goes right" eq? (:foo, :foo) test "something goes right" eq? (:foo, :foo)
@ -365,26 +427,32 @@ test "something goes wrong" {
Formally: `test <string> <expression>`. Formally: `test <string> <expression>`.
## Changing things: `ref`s Status: not yet implemented.
Ludus does not let you re-bind names. It does, however, have a type that allows for changing values over time: `ref` (short for reference--they are references to values). `ref`s are straightforward, but do require a bit more overhead than `let` bindings. The idea is that Ludus makes it obvious where mutable state is in a program, as well as where that mutable state may change. It does so elegantly, but with some guardrails that may take a little getting used to.
The type of a `ref` is, predictably, `:ref`. ## Changing things: `box`es
Ludus does not let you re-bind names. It does, however, have a type that allows for changing values over time: `box`. A box is a place to put things, it has its own identity, it can store whatever you put in it.
Syntactically and semantically, `box`es are straightforward, but do require a bit more overhead than `let` bindings. The idea is that Ludus makes it obvious where mutable state is in a program, as well as where that mutable state may change. It does so elegantly, but with some guardrails that may take a little getting used to.
The type of a `box` is, predictably, `:box`.
``` ```
ref foo = 42 & foo is now bound to a _ref that contains 42_ box foo = 42 & foo is now bound to a _box that contains 42_
add (1, foo) & panic! no match: foo is _not_ a number add (1, foo) & panic! no match: foo is _not_ a number
make! (foo, 23) & foo is now a ref containing 23 store! (foo, 23) & foo is now a box containing 23
update! (foo, inc) & foo is now a ref containing 24 update! (foo, inc) & foo is now a ref containing 24
value_of (foo) &=> 23; use value_of to get the value contained in a ref unbox (foo) &=> 23; use unbox to get the value contained in a box
``` ```
### Ending with a bang! ### Ending with a bang!
Ludus has a strong naming convention that functions that change state or could cause an explicit panic end in an exclamation point (or, in computer nerd parlance, a "bang"). So anything function that mutates the value held in a reference ends with a bang: `make!` and `update!` take bangs; `value_of` does not. Ludus has a strong naming convention that functions that change state or could cause an explicit panic end in an exclamation point (or, in computer nerd parlance, a "bang"). So anything function that mutates the value held in a reference ends with a bang: `store!` and `update!` take bangs; `unbox` does not.
This convention also includes anything that prints to the console: `print!`, `report!`, `doc!`, `update!`, `make!`, etc. This convention also includes anything that prints to the console: `print!`, `report!`, `doc!`, `update!`, `store!`, etc.
(Note that there are a few counter-examples to this: math functions that could cause a panic [in place of returning NaN] do not end with bangs: `div`, `inv`, and `mod`; each of these has variants that allow for more graceful error handling).
### Ending with a whimper? ### Ending with a whimper?
Relatedly, just about any function that returns a boolean value is a predicate function--and has a name that ends with a question mark: `eq?` tests for equality; `ref?` tells you if something is a ref or not; `lte?` is less-than-or-equal. Relatedly, just about any function that returns a boolean value is a predicate function--and has a name that ends with a question mark: `eq?` tests for equality; `box?` tells you if something is a ref or not; `lte?` is less-than-or-equal.
## Errors: panic! in the Ludus script ## Errors: panic! in the Ludus script
A special form, `panic!`, halts script execution with the expression that follows as an error message. A special form, `panic!`, halts script execution with the expression that follows as an error message.
@ -401,10 +469,11 @@ Panics also happen in the following cases:
* a function is called with arguments that do not match any of its clauses * a function is called with arguments that do not match any of its clauses
* something that is not a function or keyword is called as a function * something that is not a function or keyword is called as a function
* a called keyword is partially applied * a called keyword is partially applied
* `div` divides by zero * `div`, `inv`, or `mod` divides by zero
* `sqrt` takes the square root of a negative number
* certain error handling functions, like `unwrap!` or `assert!`, are invoked on values that cause them to panic * certain error handling functions, like `unwrap!` or `assert!`, are invoked on values that cause them to panic
In fact, the only functions in the Prelude which can cause panics are, at current, `div`, `unwrap!`, and `assert!`. In fact, the only functions in the Prelude which explicitly cause panics are, at current, `div`, `inv`, `mod`, `sqrt`, `unwrap!`, and `assert!`.
### `nil`s, not errors ### `nil`s, not errors
Ludus, however, tries to return `nil` instead of panicking a lot of the time. So, for example, attempting to get access a value at a keyword off a number, while nonsensical, will return `nil` rather than panicking: Ludus, however, tries to return `nil` instead of panicking a lot of the time. So, for example, attempting to get access a value at a keyword off a number, while nonsensical, will return `nil` rather than panicking:
@ -418,6 +487,6 @@ at (b, 12) &=> nil
``` ```
### Result tuples ### Result tuples
Operations that could fail--especially when you want some information about why--don't always return `nil` on failures. Instead of exceptions or special error values, recoverable errors in Ludus are handled instead by result tuples: `(:ok, value)` and `(:err, msg)`. So, for example, `unwrap!` takes a result tuple and either returns the value in the `:ok` case, or panics in the `:err` case. Or `assert!` will panic on a falsy value; `assert`, instead, returns a result tuple. Operations that could fail--especially when you want some information about why--don't always return `nil` on failures. Instead of exceptions or special error values, recoverable errors in Ludus are handled instead by result tuples: `(:ok, value)` and `(:err, msg)`. So, for example, `unwrap!` takes a result tuple and either returns the value in the `:ok` case, or panics in the `:err` case.
Variants of some functions that may have undesirably inexplicit behaviour are written as `{name}/safe`. So, for example, you can get a variant of `div` that returns a result tuple in `div/safe`, which returns `(:ok, result)` when everything's good; and `(:err, "division by zero")` when the divisor is 0. Or, `get/safe` will give you a result rather than returning `nil`. (Althougn `nil` punning makes this mostly unncessary. Mostly.) Variants of some functions that may have undesirably inexplicit behaviour are written as `{name}/safe`. So, for example, you can get a variant of `div` that returns a result tuple in `div/safe`, which returns `(:ok, result)` when everything's good; and `(:err, "division by zero")` when the divisor is 0.

View File

@ -9,26 +9,26 @@
& some forward declarations & some forward declarations
& TODO: fix this so that we don't need (as many of) them & TODO: fix this so that we don't need (as many of) them
fn first
fn append
fn some?
fn update!
fn string
fn join
fn neg?
fn atan/2
fn mod
fn assoc & ?
fn dict
fn get
fn unbox
fn store!
fn turn/rad
fn deg/rad
fn floor
fn and fn and
fn append
fn apply_command fn apply_command
fn assoc & ?
fn atan/2
fn deg/rad
fn dict
fn first
fn floor
fn get
fn join
fn mod
fn neg?
fn some?
fn state/call fn state/call
fn store!
fn string
fn turn/rad
fn unbox
fn update!
& the very base: know something's type & the very base: know something's type
fn type { fn type {
@ -36,6 +36,30 @@ fn type {
(x) -> base :type (x) (x) -> base :type (x)
} }
& some helper type functions
fn coll? {
"Returns true if a value is a collection: dict, list, tuple, or set."
(coll as :dict) -> true
(coll as :list) -> true
(coll as :tuple) -> true
(coll as :set) -> true
(_) -> false
}
fn ordered? {
"Returns true if a value is an indexed collection: list or tuple."
(coll as :list) -> true
(coll as :tuple) -> true
(_) -> false
}
fn assoc? {
"Returns true if a value is an associative collection: a dict or a pkg."
(assoc as :dict) -> true
(assoc as :pkg) -> true
(_) -> false
}
& ...and if two things are the same & ...and if two things are the same
fn eq? { fn eq? {
"Returns true if all arguments have the same value." "Returns true if all arguments have the same value."
@ -166,25 +190,10 @@ fn list? {
} }
fn list { fn list {
"Takes a value and returns it as a list. For values, it simply wraps them in a list. For collections, conversions are as follows. A tuple->list conversion preservers order and length. Unordered collections do not preserve order. Associative collections return lists of (key, value) tuples." "Takes a value and returns it as a list. For values, it simply wraps them in a list. For collections, conversions are as follows. A tuple->list conversion preservers order and length. Unordered collections do not preserve order: sets and dicts don't have predictable or stable ordering in output. Dicts return lists of (key, value) tuples."
(x) -> base :to_list (x) (x) -> base :to_list (x)
} }
& TODO: make this work with Janet base
fn set {
"Takes an ordered collection--list or tuple--and turns it into a set."
(xs as :list) -> base :into (${}, xs)
(xs as :tuple) -> base :into (${}, xs)
}
fn set? {
"Returns true if a value is a set."
(xs as :set) -> true
(_) -> false
}
& add a contains? or has? function
fn fold { fn fold {
"Folds a list." "Folds a list."
(f as :fn, xs as :list) -> fold (f, xs, f ()) (f as :fn, xs as :list) -> fold (f, xs, f ())
@ -245,30 +254,29 @@ fn concat {
(xs, ys, ...zs) -> fold (concat, zs, concat (xs, ys)) (xs, ys, ...zs) -> fold (concat, zs, concat (xs, ys))
} }
& the console: sending messages to the outside world
& the console is *both* something we send to the host language's console
& ...and also a list of messages.
& box console = []
& fn flush! { fn set {
& "Clears the console, and returns the messages." "Takes an ordered collection--list or tuple--and turns it into a set."
& () -> { (xs as :list) -> fold (append, xs, ${})
& let msgs = unbox (console) (xs as :tuple) -> do xs > list > set
& store! (console, []) }
& msgs
& }
& }
& fn add_msg! { fn set? {
& "Adds a message to the console." "Returns true if a value is a set."
& (msg as :string) -> update! (console, append (_, msg)) (xs as :set) -> true
& (msgs as :list) -> { (_) -> false
& base :print! (("adding msg", msgs)) }
& let msg = do msgs > map (string, _) > join
& base :print! (("msg: ", msg)) fn contains? {
& update! (console, append (_, msg)) "Returns true if a set or list contains a value."
& } (value, set as :set) -> bool (base :get (set, value))
& } (value, list as :list) -> contains? (value, set (list))
}
fn omit {
"Returns a new set with the value omitted."
(value, s as :set) -> base :disj (s, value)
}
fn print! { fn print! {
"Sends a text representation of Ludus values to the console." "Sends a text representation of Ludus values to the console."
@ -283,15 +291,6 @@ fn show {
(x) -> base :show (x) (x) -> base :show (x)
} }
fn prn! {
"Prints the underlying Clojure data structure of a Ludus value."
(x) -> {
base :prn (x)
& add_msg! (x)
:ok
}
}
fn report! { fn report! {
"Prints a value, then returns it." "Prints a value, then returns it."
(x) -> { (x) -> {
@ -299,7 +298,7 @@ fn report! {
x x
} }
(msg as :string, x) -> { (msg as :string, x) -> {
print! (concat (msg, show (x))) print! (concat ("{msg} ", show (x)))
x x
} }
} }
@ -332,7 +331,7 @@ fn join {
([]) -> "" ([]) -> ""
([str as :string]) -> str ([str as :string]) -> str
(strs as :list) -> join (strs, "") (strs as :list) -> join (strs, "")
([str], separator as :string) -> str ([str as :string], separator as :string) -> str
([str, ...strs], separator as :string) -> fold ( ([str, ...strs], separator as :string) -> fold (
fn (joined, to_join) -> concat (joined, separator, to_join) fn (joined, to_join) -> concat (joined, separator, to_join)
strs strs
@ -398,13 +397,7 @@ fn sentence {
(strs as :list) -> join (strs, " ") (strs as :list) -> join (strs, " ")
} }
&&& boxes: mutable state and state changes
& in another prelude, with a better actual base language than Java (thanks, Rich), counting strings would be reasonable but complex: count/bytes, count/points, count/glyphs. Java's UTF16 strings make this unweildy.
& TODO: add trim, trim/left, trim/right; pad/left, pad/right
& ...also a version of at,
&&& references: mutable state and state changes
fn box? { fn box? {
"Returns true if a value is a box." "Returns true if a value is a box."
@ -650,17 +643,17 @@ fn at {
fn first { fn first {
"Returns the first element of a list or tuple." "Returns the first element of a list or tuple."
(xs) -> at (xs, 0) (xs) if ordered? (xs) -> at (xs, 0)
} }
fn second { fn second {
"Returns the second element of a list or tuple." "Returns the second element of a list or tuple."
(xs) -> at (xs, 1) (xs) if ordered? (xs) -> at (xs, 1)
} }
fn last { fn last {
"Returns the last element of a list or tuple." "Returns the last element of a list or tuple."
(xs) -> at (xs, dec (count (xs))) (xs) if ordered? (xs) -> at (xs, dec (count (xs)))
} }
fn butlast { fn butlast {
@ -731,9 +724,6 @@ fn or {
(x, y, ...zs) -> fold (or, zs, base :or (x, y)) (x, y, ...zs) -> fold (or, zs, base :or (x, y))
} }
&&& associative collections: dicts, structs, namespaces
& TODO?: get_in, update_in, merge
& TODO?: consider renaming these: put & take, not assoc/dissoc
fn assoc { fn assoc {
"Takes a dict, key, and value, and returns a new dict with the key set to value." "Takes a dict, key, and value, and returns a new dict with the key set to value."
() -> #{} () -> #{}
@ -791,30 +781,6 @@ fn diff {
} }
} }
fn coll? {
"Returns true if a value is a collection: dict, list, pkg, tuple, or set."
(coll as :dict) -> true
(coll as :list) -> true
(coll as :tuple) -> true
(coll as :set) -> true
(coll as :pkg) -> true
(_) -> false
}
fn ordered? {
"Returns true if a value is an indexed collection: list or tuple."
(coll as :list) -> true
(coll as :tuple) -> true
(_) -> false
}
fn assoc? {
"Returns true if a value is an associative collection: a dict or a pkg."
(assoc as :dict) -> true
(assoc as :pkg) -> true
(_) -> false
}
& TODO: consider merging `get` and `at` & TODO: consider merging `get` and `at`
fn get { fn get {
"Takes a key, dict, and optional default value; returns the value at key. If the value is not found, returns nil or the default value." "Takes a key, dict, and optional default value; returns the value at key. If the value is not found, returns nil or the default value."
@ -843,15 +809,11 @@ fn dict? {
(_) -> false (_) -> false
} }
& TODO: make this less awkward once we have tail recursion
fn each! { fn each! {
"Takes a list and applies a function, presumably with side effects, to each element in the list. Returns nil." "Takes a list and applies a function, presumably with side effects, to each element in the list. Returns nil."
(f! as :fn, []) -> nil (f! as :fn, []) -> nil
(f! as :fn, [x]) -> { f! (x); nil } (f! as :fn, [x]) -> { f! (x); nil }
(f! as :fn, [...xs]) -> loop (xs) with { (f! as :fn, [x, ...xs]) -> { f! (x); each! (f!, xs) }
([x]) -> { f! (x); nil }
([x, ...xs]) -> { f! (x); recur (xs) }
}
} }
&&& Trigonometry functions &&& Trigonometry functions
@ -938,18 +900,38 @@ fn atan/2 {
} }
fn mod { fn mod {
"Returns the modulus of num and div. Truncates towards negative infinity." "Returns the modulus of num and div. Truncates towards negative infinity. Panics if div is 0."
(num as :number, 0) -> panic! "Division by zero."
(num as :number, div as :number) -> base :mod (num, div) (num as :number, div as :number) -> base :mod (num, div)
} }
fn mod/0 {
"Returns the modulus of num and div. Truncates towards negative infinity. Returns 0 if div is 0."
(num as :number, 0) -> 0
(num as :number, div as :number) -> base :mod (num, div)
}
fn mod/safe {
"Returns the modulus of num and div in a result tuple, or an error if div is 0. Truncates towards negative infinity."
(num as :number, 0) -> (:err, "Division by zero.")
(num as :number, div as :number) -> (:ok, base :mod (num, div))
}
fn square { fn square {
"Squares a number." "Squares a number."
(x as :number) -> mult (x, x) (x as :number) -> mult (x, x)
} }
fn sqrt { fn sqrt {
"Returns the square root of a number." "Returns the square root of a number. Panics if the number is negative."
(x as :number) -> base :sqrt (x) (x as :number) if not (neg? (x)) -> base :sqrt (x)
}
fn sqrt/safe {
"Returns a result containing the square root of a number, or an error if the number is negative."
(x as :number) -> if not (neg? (x))
then (:ok, base :sqrt (x))
else (:err, "sqrt of negative number")
} }
fn sum_of_squares { fn sum_of_squares {
@ -957,18 +939,21 @@ fn sum_of_squares {
() -> 0 () -> 0
(x as :number) -> square (x) (x as :number) -> square (x)
(x as :number, y as :number) -> add (square (x), square (y)) (x as :number, y as :number) -> add (square (x), square (y))
(x, y, ...zs) -> fold (sum_of_squares, zs, sum_of_squares (x, y)) (x, y, ...zs) -> fold (
fn (sum, z) -> add (sum, square (z))
zs
sum_of_squares (x, y))
} }
fn dist { fn dist {
"Returns the distance from the origin to a point described by (x, y)." "Returns the distance from the origin to a point described by x and y, or by the vector (x, y)."
(x as :number, y as :number) -> sqrt (sum_of_squares (x, y)) (x as :number, y as :number) -> sqrt (sum_of_squares (x, y))
((x, y)) -> dist (x, y) ((x, y)) -> dist (x, y)
} }
&&& more number functions &&& more number functions
fn random { fn random {
"Returns a random number. With zero arguments, returns a random number between 0 (inclusive) and 1 (exclusive). With one argument, returns a random number between 0 and n. With two arguments, returns a random number between m and n. Alternately, given a list, it returns a random member of that list." "Returns a random something. With zero arguments, returns a random number between 0 (inclusive) and 1 (exclusive). With one argument, returns a random number between 0 and n. With two arguments, returns a random number between m and n. Alternately, given a collection (list, dict, set), it returns a random member of that collection."
() -> base :random () () -> base :random ()
(n as :number) -> mult (n, random ()) (n as :number) -> mult (n, random ())
(m as :number, n as :number) -> add (m, random (sub (n, m))) (m as :number, n as :number) -> add (m, random (sub (n, m)))
@ -980,6 +965,7 @@ fn random {
let key = do d > keys > random let key = do d > keys > random
get (key, d) get (key, d)
} }
(s as :set) -> do s > list > random
} }
fn random_int { fn random_int {
@ -1048,10 +1034,12 @@ fn unwrap_or {
fn assert! { fn assert! {
"Asserts a condition: returns the value if the value is truthy, panics if the value is falsy. Takes an optional message." "Asserts a condition: returns the value if the value is truthy, panics if the value is falsy. Takes an optional message."
(value) -> if value then value else panic! string ("Assert failed:", value) (value) -> if value
then value
else panic! "Assert failed: {value}"
(msg, value) -> if value (msg, value) -> if value
then value then value
else panic! string ("Assert failed: ", msg, " with ", value) else panic! "Assert failed: {msg} with {value}"
} }
&&& Turtle & other graphics &&& Turtle & other graphics
@ -1198,8 +1186,6 @@ fn back! {
let bk! = back! let bk! = back!
& turtles, like eveyrthing else in Ludus, use turns by default,
& not degrees
fn left! { fn left! {
"Rotates the turtle left, measured in turns. Alias: lt!" "Rotates the turtle left, measured in turns. Alias: lt!"
(turns as :number) -> add_command! ((:left, turns)) (turns as :number) -> add_command! ((:left, turns))
@ -1374,6 +1360,7 @@ pkg Prelude {
coll? & dicts lists sets tuples coll? & dicts lists sets tuples
colors & turtles colors & turtles
concat & string list set concat & string list set
contains? & list set
cos & math cos & math
count & string list set tuple dict count & string list set tuple dict
dec & math dec & math
@ -1430,6 +1417,8 @@ pkg Prelude {
max & math max & math
min & math min & math
mod & math mod & math
mod/0
mod/safe
mult & math mult & math
neg & math neg & math
neg? & math neg? & math
@ -1439,6 +1428,7 @@ pkg Prelude {
odd? & math odd? & math
ok & results ok & results
ok? & results ok? & results
omit & set
or & bool or & bool
ordered? & lists tuples strings ordered? & lists tuples strings
p5_calls & turtles p5_calls & turtles
@ -1455,7 +1445,6 @@ pkg Prelude {
pos? & math pos? & math
position & turtles position & turtles
print! & environment print! & environment
& prn! & environment
pu! & turtles pu! & turtles
pw! & turtles pw! & turtles
rad/deg & math rad/deg & math
@ -1480,6 +1469,8 @@ pkg Prelude {
some & values some & values
some? & values some? & values
split & strings split & strings
sqrt & math
sqrt/safe & math
square & math square & math
state & environment state & environment
store! & boxes store! & boxes

File diff suppressed because one or more lines are too long

View File

@ -69,6 +69,13 @@
(pairs dict)) (pairs dict))
", ")) ", "))
(defn- set-show [sett]
(def prepped (merge sett))
(set (prepped :^type) nil)
(def shown (map show (keys prepped)))
(string/join shown ", ")
)
(defn- show* [x] (defn- show* [x]
(case (ludus/type x) (case (ludus/type x)
:nil "nil" :nil "nil"
@ -76,7 +83,7 @@
:tuple (string "(" (string/join (map show x) ", ") ")") :tuple (string "(" (string/join (map show x) ", ") ")")
:list (string "[" (string/join (map show x) ", ") "]") :list (string "[" (string/join (map show x) ", ") "]")
:dict (string "#{" (dict-show x) "}") :dict (string "#{" (dict-show x) "}")
:set (string "${" (string/join (map show (keys x)) ", ") "}") :set (string "${" (set-show x) "}")
:box (string "box " (x :name) " [ " (show (x :^value)) " ]") :box (string "box " (x :name) " [ " (show (x :^value)) " ]")
:pkg (show-pkg x) :pkg (show-pkg x)
(stringify x))) (stringify x)))

View File

@ -22,14 +22,15 @@
(string/join (map toc-entry sorted-names) "&nbsp;&nbsp;&nbsp; ")) (string/join (map toc-entry sorted-names) "&nbsp;&nbsp;&nbsp; "))
(def topics { (def topics {
"math" ["abs" "add" "angle" "atan/2" "between?" "ceil" "cos" "dec" "deg/rad" "deg/turn" "dist" "div" "div/0" "div/safe" "even?" "floor" "gt?" "gte?" "heading/vector" "inc" "inv" "inv/0" "inv/safe" "lt?" "lte?" "max" "min" "mod" "mult" "neg" "neg?" "odd?" "pi" "pos?" "rad/deg" "rad/turn" "random" "random_int" "range" "round" "sin" "square" "sub" "sum_of_squares" "tan" "tau" "turn/deg" "turn/rad" "zero?"] "math" ["abs" "add" "angle" "atan/2" "between?" "ceil" "cos" "dec" "deg/rad" "deg/turn" "dist" "div" "div/0" "div/safe" "even?" "floor" "gt?" "gte?" "heading/vector" "inc" "inv" "inv/0" "inv/safe" "lt?" "lte?" "max" "min" "mod" "mod/0" "mod/safe" "mult" "neg" "neg?" "odd?" "pi" "pos?" "rad/deg" "rad/turn" "random" "random_int" "range" "round" "sin" "sqrt" "sqrt/safe" "square" "sub" "sum_of_squares" "tan" "tau" "turn/deg" "turn/rad" "zero?"]
"boolean" ["and" "bool" "bool?" "false?" "not" "or"] "boolean" ["and" "bool" "bool?" "false?" "not" "or" "true?"]
"dicts" ["any?" "assoc" "assoc?" "coll?" "count" "dict" "dict?" "diff" "dissoc" "empty?" "get" "keys" "random" "update" "values"] "dicts" ["any?" "assoc" "assoc?" "coll?" "count" "dict" "dict?" "diff" "dissoc" "empty?" "get" "keys" "random" "update" "values"]
"lists" ["any?" "append" "at" "butlast" "coll?" "concat" "count" "each!" "empty?" "filter" "first" "fold" "join" "keep" "last" "list" "list?" "map" "ordered?""random" "range" "rest" "second" "sentence" "slice"] "lists" ["any?" "append" "at" "butlast" "coll?" "concat" "count" "each!" "empty?" "filter" "first" "fold" "join" "keep" "last" "list" "list?" "map" "ordered?" "random" "range" "rest" "second" "sentence" "slice"]
"sets" ["any?" "append" "coll?" "concat" "count" "empty?" "random" "set" "set?"] "sets" ["any?" "append" "coll?" "concat" "contains?" "count" "empty?" "omit" "random" "set" "set?"]
"tuples" ["any?" "at" "coll?" "count" "empty?" "first" "ordered?" "second" "tuple?"]
"strings" ["any?" "concat" "count" "downcase" "empty?" "join" "sentence" "show" "slice" "split" "string" "string?" "strip" "trim" "upcase" "words"] "strings" ["any?" "concat" "count" "downcase" "empty?" "join" "sentence" "show" "slice" "split" "string" "string?" "strip" "trim" "upcase" "words"]
"types and values" ["assoc?" "bool?" "coll?" "dict?" "eq?" "fn?" "keyword?" "list?" "neq?" "nil?" "number?" "ordered?" "show" "some" "some?" "string?" "type"] "types and values" ["assoc?" "bool?" "box?" "coll?" "dict?" "eq?" "fn?" "keyword?" "list?" "neq?" "nil?" "number?" "ordered?" "set?" "show" "some" "some?" "string?" "tuple?" "type"]
"boxes and state" ["unbox" "store!" "update!"] "boxes and state" ["box?" "unbox" "store!" "update!"]
"results" ["err" "err?" "ok" "ok?" "unwrap!" "unwrap_or"] "results" ["err" "err?" "ok" "ok?" "unwrap!" "unwrap_or"]
"errors" ["assert!"] "errors" ["assert!"]
"turtle graphics" ["back!" "background!" "bk!" "clear!" "colors" "fd!" "forward!" "goto!" "heading" "heading/vector" "home!" "left!" "lt!" "pc!" "pd!" "pencolor" "pencolor!" "pendown!" "pendown?" "penup!" "penwidth" "penwidth!" "position" "pu!" "pw!" "render_turtle!" "reset_turtle!" "right!" "rt!" "turtle_state"] "turtle graphics" ["back!" "background!" "bk!" "clear!" "colors" "fd!" "forward!" "goto!" "heading" "heading/vector" "home!" "left!" "lt!" "pc!" "pd!" "pencolor" "pencolor!" "pendown!" "pendown?" "penup!" "penwidth" "penwidth!" "position" "pu!" "pw!" "render_turtle!" "reset_turtle!" "right!" "rt!" "turtle_state"]
@ -54,18 +55,19 @@
(string/join topics-entries "\n"))) (string/join topics-entries "\n")))
(defn compose-entry [name] (defn compose-entry [name]
(def header (string "### " name "\n")) (def header (string "\n### " name "\n"))
(def the-doc (get with-docs name)) (def the-doc (get with-docs name))
(when (= "No documentation available." the-doc) (when (= "No documentation available." the-doc)
(break (string header the-doc "\n"))) (break (string header the-doc "\n")))
(def lines (string/split "\n" the-doc)) (def lines (string/split "\n" the-doc))
(def description (last lines)) (def description (last lines))
(def patterns (string/join (slice lines 1 (-> lines length dec)) "\n")) (def patterns (string/join (slice lines 1 (-> lines length dec)) "\n"))
(string header description "\n```\n" patterns "\n```\n")) (def backto "[Back to top.](#ludus-prelude-documentation)\n")
(string header description "\n```\n" patterns "\n```\n" backto))
(compose-entry "update") (compose-entry "update")
(def entries (string/join (map compose-entry sorted-names) "\n\n")) (def entries (string/join (map compose-entry sorted-names) "\n---"))
(def doc-file (string (def doc-file (string
``` ```

View File

@ -49,37 +49,12 @@
(set (out :draw) (post :draw)) (set (out :draw) (post :draw))
(-> out j/encode string)) (-> out j/encode string))
# (comment (comment
(do # (do
(def source ` (def source `
fn strip_punctuation { let myset = ${1, 2, 3, 3, 2}
("{x},{y}") -> strip_punctuation ("{x}{y}") omit (2, myset)
("{x}.{y}") -> strip_punctuation ("{x}{y}") myset
("{x};{y}") -> strip_punctuation ("{x}{y}")
("{x}:{y}") -> strip_punctuation ("{x}{y}")
("{x}?{y}") -> strip_punctuation ("{x}{y}")
("{x}!{y}") -> strip_punctuation ("{x}{y}")
(x) -> x
}
fn trim_left {
(" {x}") -> trim_left ("{x}")
("\n{x}") -> trim_left ("{x}")
("\t{x}") -> trim_left ("{x}")
(x) -> x
}
fn trim_right {
("{x} ") -> trim_right ("{x}")
("{x}\n") -> trim_right ("{x}")
("{x}\t") -> trim_right ("{x}")
(x) -> x
}
fn trim (x) -> do x > trim_left > trim_right
trim_left ("
foo")
`) `)
(def out (-> source (def out (-> source
ludus ludus