Accessors
Accessor is way to reach inside lists, maps and other complex structures:
$obj := { tags: ["indie", "adventure", "puzzle"] }
put $obj.tags[2]
# => puzzle
In this example .tag is a field accessor and
[2] is an index accessor.
Field
Field accessors are primarily used to access fields of maps. A field name can contain letters, digits and underscore; to access field names with other symbols, use index accessor.
$pod = {
metadata: {
name: "nginx",
labels: {},
},
spec: {
containers: [{
image: "nginx:stable"
}],
},
}
| access nested fields | |
update nested fields, create a new field in labels |
|
| value semantics is preserved: when changing a variable, only that variable changes, other variables stay intact | |
Index
Index accessors can be used on lists to access n-th element, or on maps to access fields. Negative indices in lists do the reverse order, i.e. -1 is the index of the last element.
| access a list at O(1) | |
| access a map at O(1) | |
| complex keys in maps are allowed. However, this should probably be avoided for big lists and maps, as hash and comparison functions will be called on each lookup | |
| 2D array demo: given two strings, find edit distance a.k.a Levinshtein distance. Computation complexity is O(N · M), where N and M are lengths of strings | |
Formatters
Format accessors are used to convert between syshell types and various text formats like JSON, or smaller things like numbers and dates. Here is a full list of formatters.
For each format there are two accessors: : to convert
from a text format to a syshell value, and @ to convert in
the opposite direction.
:slashes splits an incoming string by slash |
|
@slashes join a list of strings by slash |
|
formatters can be used on in the assignments too. In this case, it
first uses :slashes to get access to a list, then updates
the list in-place and uses @slashes to convert it back to a
string |
|
Path
Accessors can be stored as a value, which is useful for functions arguments and configuration.
create a path with $ following accessors |
|
apply a path on an expression using
.$pod is defined above in the Field Accessor
section |
|
sort a list of maps by the birthday field using sort |
|
Slice
For lists it's possible to take a slice of them using [begin..end], the specified range is half open, i.e. begin is included, while end is not. Both begin and end can be omitted, in this case 0 and list length will be assumed. Negative indices work the same as in the index accessor. Slicing is O(1).
| get second to fourth elements | |
| slicing from 0 to len is equivalent to the original list. | |
| pop the first element | |
| pop the last element | |
Append
Assigning to a list without specifying index (e.g.
$list[] = 5) will append provided value to this list.
Appends are amortized O(1).
| append an element to a list | |
| appends can be used together with formatters | |