Janet 1.39.1-e9c6678 Documentation
(Other Versions:
1.38.0
1.37.1
1.36.0
1.35.0
1.34.0
1.31.0
1.29.1
1.28.0
1.27.0
1.26.0
1.25.1
1.24.0
1.23.0
1.22.0
1.21.0
1.20.0
1.19.0
1.18.1
1.17.1
1.16.1
1.15.0
1.13.1
1.12.2
1.11.1
1.10.1
1.9.1
1.8.1
1.7.0
1.6.0
1.5.1
1.5.0
1.4.0
1.3.1
)
misc
Miscellaneous utilities for Janet.
Dedent
Remove indentation after concatenating the arguments.
(misc/dedent ``
ho
hoho
hohoho
``)
set*
Allow parallel mutation of multiple mutable variables. (All right hand sides are computed before setting the left hand sides.)
# you can use it with vars
(var a 2)
(var b 3)
(misc/set* [a b] [b (+ a b)])
[a b] => [3 5]
# or you can use it with arrays, for example:
(def x @[2 3])
(misc/set* [[x 0] [x 1]] [(in x 1) (+ (in x 0) (in x 1))])
x => @[3 5]
print-table
Given a list of tables containing column keys with corresponding row values, print its content to stdout in a human-readable tabular layout. For example:
(misc/print-table [
{:x "abc" :y "123"}
{:x "hello" :y "world"}
{:x "banana" :y "orange"}
{:x "cat" :y "dog"}])
produces:
x y
════════════════
abc 123
hello world
banana orange
cat dog
map-keys
Returns new table with function applied to table's keys recursively.
(misc/map-keys string {1 2 3 4})
# => @{"1" 2 "3" 4}
map-vals
Returns new table with function applied to table's values.
(misc/map-vals string {1 2 3 4})
# => @{1 "2" 3 "4"}
select-keys
Returns new table with selected keys from dictionary.
(misc/select-keys {1 2 3 4 5 6} [1 5])
# => @{1 2 5 6}
cond->
Threading conditional macro. It takes value to mutate, and clauses pairs with a condition and a operation to which the value is put as the first argument. All conditions are tried and for truthy conditions the operation is performed.
Returns the value mutated if any condition is truthy.
(misc/cond-> @{:a :b}
(pos? 1) (put :a :c)
(pos? 0) (put :a :d))
# => @{:a :c}
cond->>
Threading conditional macro. It takes value to mutate, and clauses pairs of a condition and a operation to which the value, is put as the last argument. All conditions are tried and for truthy the operation is performed.
Returns mutated value if any condition is truthy.
(misc/cond->> @{:a :b}
(pos? 1) (merge {:d :e})
(pos? 0) (merge {:e :f}))
# => @{:a :b :d :e}
make
Convenience macro for creating new table from even number of kvs pairs in a variadic pairs arguments and setting its prototype to prototype.
Factory function for creating new objects from prototypes.
(def Proto @{:greet (fn [self] (string "Hello " (self :name)))})
(def t (misc/make Proto :name "pepe"))
(:greet t)
# => "Hello pepe"
do-var
Convenience macro for defining varible with value before body and returning it after evaluating body, that presumably modifies variable.
(misc/do-var res 0 (set res 100) (++ res))
# => 101
do-def
Convenience macro for defining constant with value before body and returning it after evaluating body, that presumably modifies the const refered content. For example buffer, table or array.
(misc/do-def res @"" (buffer/push res "a"))
# => @"a"
capout
Captures the standart output of the variadic body and returns it as a buffer.
(misc/capout
(def p "HOHOHO")
(prin p))
# => @"HOHOHO"
caperr
Captures the standart error output of the variadic body and returns it as a buffer.
(misc/caperr
(def p "HOHOHO")
(eprin p))
# => @"HOHOHO"
vars
Defines many variables as in let bindings, but without creating new scope.
(do (misc/vars a 2 b 1) a)
# => 2
always
Return a function that discards any arguments and always returns its argument.
(def always-true (misc/always true))
(always-true)
# => true
(always-true)
# => true
(always-true 1 2 3)
# => true
second
Get the second element from an indexed data structure.
(misc/second [1 2 3])
# => 2
third
Get the third element from an indexed data structure.
(misc/third [1 2 3])
# => 3
penultimate
Get the second-to-last element from an indexed data structure.
(misc/penultimate [1 2 3 4 5])
# => 4
antepenultimate
Get the third-to-last element from an indexed data structure.
(misc/antepenultimate [1 2 3 4 5])
# => 3
int/
Perform an integer division.
(misc/int/ 11 3) 3
gett
Recursive macro get. Similar to get-in, but keys are variadic argument.
(misc/gett {:a {:b {:c :c}}} :a :b :c)
# => :c
until Repeat the body while the condition is false.
Equivalent to `(while (not cnd) ;body)`.
(misc/do-var res 0 (misc/until (> res 3) (++ res)))
# => 4
table-filter
Filter a key-value structure info a table. Semantics are the same as for built-in filter, except that predicate takes two arguments (key and value.)
Does not consider prototypes.
(misc/table-filter |(even? $1) @{:zero 0 :one 1 :two 2 :three 3})
# => @{:zero 0 :two 2}
buffer/reverse
Reverse a buffer in-place.
(misc/buffer/reverse @"abcd")
# => @"dcba"
string->int
Parses an integer in the given base. Defaults to decimal (base 10). Differs from scan-number in that this does not recognize floating point notation.
(misc/string->int "101" 2)
# => 2r101
int->string
Stringify an integer in a particular base. Defaults to decimal (base 10).
(misc/int->string 2r11011011 2)
# => "11011011"
insert-sorted
Insert elements in array such that it remains sorted by the comparator. If array is not sorted beforehand, the results are undefined. Returns array.
(misc/insert-sorted @[1 2 3 5] < 4)
# => @[1 2 3 4 5]
insert-sorted-by
Insert elements in array such that it remains sorted by the value returned when function is called with the element, comparing the values with <. If the array is not sorted beforehand, the results are undefined. Returns the array.
(misc/insert-sorted-by @[1 2 3 5] identity 4)
# => @[1 2 3 4 5]
Reference
misc/always misc/antepenultimate misc/binary-search misc/binary-search-by misc/caperr misc/capout misc/cond-> misc/cond->> misc/dedent misc/defs misc/dfs misc/do-def misc/do-var misc/format-table misc/gett misc/insert-sorted misc/insert-sorted-by misc/int->string misc/int/ misc/log misc/make misc/make-id misc/map-keys misc/map-keys-flat misc/map-vals misc/merge-sorted misc/merge-sorted-by misc/penultimate misc/print-table misc/randomize-array misc/second misc/select-keys misc/set* misc/string->int misc/table-filter misc/third misc/trim-prefix misc/trim-suffix misc/until misc/vars
(always x) Return a function that discards any arguments and always returns `x`.
(antepenultimate xs) Get the third-to-last element from an indexed data structure.
(binary-search x arr &opt <?) Returns the index of `x` in a sorted array or tuple or the index of the next item if `x` is not present. This is the correct insert index for `x` within `arr`. If a `<?` comparator is given, the search uses that to compare elements, otherwise uses `<`.
(binary-search-by x arr f) Returns the index of `x` in an array or tuple which has been sorted by a mapping function `f`, or the index of the next item if `x` is not present. This is the correct insert index for `x` within `arr`.
(caperr & body) Captures the standard error output of the variadic `body` and returns it as a buffer.
(capout & body) Captures the standard output of the variadic `body` and returns it as a buffer.
(cond-> val & clauses) Threading conditional macro. It takes `val` to mutate, and `clauses` pairs with condition and operation to which `val`, is passed as first argument. All conditions are tried and for truthy conditions the operation is executed. Returns the value mutated if any condition is truthy.
(cond->> val & clauses) Threading conditional macro. It takes `val` to mutate, and `clauses` pairs of condition and operation to which `val`, is passed as last argument. All conditions are tried and for truthy conditions the operation is executed. Returns mutated value if any condition is truthy.
(dedent & xs) Remove indentation after concatenating the arguments. Works by removing leading whitespace, and then removing that same pattern of whitespace after new lines.
(defs & bindings) Defines many constants as in let `bindings`, but without creating a new scope.
(dfs data visit-leaf &opt node-before node-after get-children seen) Do a depth first, pre-order traversal over a data structure. Also allow for callbacks before and after visiting the children of a node. Also allow for a custom `get-children` function to change traversal as needed. Will detect cycles if an empty table is passed as the `seen` parameter, which is used to cache values that have been visited.
(do-def c d & body) Convenience macro for defining constant named `c` with value `d` before `body` and returning it after evaluating `body`, that presumably modifies the content referred to by `c`. For example, a buffer, table or array.
(do-var v d & body) Convenience macro for defining variable named `v` with value `d` before `body` and returning it after evaluating `body`, that presumably modifies `v`.
(format-table buf-into data &opt columns header-mapping column-mapping) Same as print-table but pushes table into a buffer.
(gett ds & keyz) Recursive macro (get). Similar to get-in, but `keyz` is variadic.
(insert-sorted arr <? & xs) Insert elements in `arr` such that it remains sorted by the comparator. If `arr` is not sorted beforehand, the results are undefined. Returns `arr`.
(insert-sorted-by arr f & xs) Insert elements in `arr` such that it remains sorted by the value returned when `f` is called with the element, comparing the values with `<`. If `arr` is not sorted beforehand, the results are undefined. Returns `arr`.
(int->string int &opt base) Stringify an integer in a particular base. Defaults to decimal (base 10).
(log level & args) Print to a dynamic binding stream if that stream is set, otherwise do nothing. Evaluate to nil. For example, `(log :err "value error: %V" my-value)` will print to `(dyn :err)` only if `(dyn :err)` has been set.
(make prototype & pairs) Convenience macro for creating new table from even number of kvs pairs in variadic `pairs` arguments and setting its prototype to `prototype`. Factory function for creating new objects from prototypes.
(make-id &opt prefix) Create a random, printable keyword id with 10 bytes of entropy with an optional prefix.
(map-keys f data) Returns new table with function `f` applied to `data`'s keys recursively.
(map-keys-flat f data) Returns new table with function `f` applied to `data`'s keys without recursing.
(map-vals f data) Returns new table with function `f` applied to `data`'s values.
(merge-sorted a b &opt <?) Merges two sorted arrays so that the result remains sorted, using an optional comparator. If no comparator is given, `<` is used.
(merge-sorted-by a b f) Merges two sorted arrays so that result remains sorted when `f` is called on each element, comparing the values with `<`.
(penultimate xs) Get the second-to-last element from an indexed data structure.
(print-table data &opt columns header-mapping column-mapping) Iterate through the rows of a data structure and print a table in a human readable way, with padding and heading information. Can optionally provide a function used to print a row, as well as optionally select column keys for each row. Lastly, a `header-mapping` dictionary can be provided that changes the printed header names by mapping column keys to the desired header name. If no mapping is found, then the column key will be used as the header name. Returns nil.
(randomize-array arr &opt rng) Randomizes array using the fisher-yates shuffle, takes an optional random number generator.
(select-keys data keyz) Returns new table with selected `keyz` from dictionary `data`.
(set* tgts exprs) Parallel `set` function. Takes a list of targets and expressions, evaluates all the expressions, and then assigns them to the targets. Each target can be a variable or a 2-tuple, just like in the normal `set` special form.
(string->int str &opt base) Parse an integer in the given base. Defaults to decimal (base 10). Differs from scan-number in that this does not recognize floating point notation.
(table-filter pred dict) Filter a key-value structure into a table. Semantics are the same as for built-in `filter`, except that `pred` takes two arguments (key and value). Does not consider prototypes.
(trim-prefix prefix str) Trim the specified prefix of a string if it has one
(trim-suffix suffix str) Trim the specified suffix of a string if it has one
(until cnd & body) Repeat `body` while the `cnd` is false. Equivalent to (while (not cnd) ;body).
(vars & bindings) Defines many variables as in let `bindings`, but without creating a new scope.