Destructuring in let
Bind the parts of a list, vector, sorted map or record in one let or let* binding.
A let or let* binding can have a pattern in place of a name. The value must fit the pattern, and each name in the pattern is bound. Use it to take a value apart in one step, in place of a chain of nth, get or field calls.
Binding patterns are in ELPS v1.93.0 and later. Every example on this page runs in your browser. Edit an example to see the new result.
Syntax
(let ((name value) ; a plain binding, as before
(pattern value)) ; a binding pattern
body...)
- A symbol in the name position is a name, as before.
_is a name too. - Any other value in the name position is a pattern.
- The patterns are the ones that
matchtakes, with the same rules. [x 1]and(x 1)are the same binding. The square brackets only make the binding easier to read.
Take a list apart
Use &rest to bind the other items as a new list:
A function that returns more than one value can return a list. The caller binds each part by name:
Take a vector apart
A list pattern does not fit a vector. Use a vector pattern for a value that vector or a JSON array gives.
Read keys from a sorted map
A sorted map pattern binds the value of each key. The map can have other keys. This is the usual way to read a JSON object.
Patterns can hold other patterns. This binding reads two levels of a JSON document:
Check a type
[name T] binds name only if the value has type T. In a binding, the pattern is the name, so it is in square brackets two times.
Read fields from a record
A record pattern binds the fields of a record object. For record types, see the s:make-record section of the libschema README.
let and let*
In let, every value is evaluated first. Then the patterns are matched and the names are bound. A value cannot use a name from another binding of the same let.
In let*, each binding can use the names of the bindings before it, pattern names included.
When the value does not fit
A value that does not fit its pattern raises match-error, a child of error. The message names the pattern and the type of the value. The example below shows the error. Remove the 3 to make the value fit.
Catch match-error with handler-bind when bad input is possible:
To choose between shapes, use match. A binding has only one pattern, so a :when guard in a binding is an error.
Rules
| Rule | Detail |
|---|---|
| Plain names | A symbol binding works and costs what it did before patterns. |
| No fit | A value that does not fit raises match-error. |
| Guards | A :when guard in a binding is an error. |
Scope in let |
Every value is evaluated first, in the scope around the let. Then the names are bound. |
Scope in let* |
A value, and a type in a pattern, can use the bindings before it. |
| Cost | A pattern binding costs one step for each pattern node tried, the same as match. |
The full reference is the "Binding patterns" section of the ELPS language reference.