Logical and comparison operators
(!=) a b is 'a → 'a → boolean,
Returns true when
a and
b values are not equal (and false otherwise).
It is internally implemented on most data types using .equals()
method on the corresponding JVM value.
a | - | first value |
b | - | second value |
(<) a b is ^j → ^j → boolean,
Returns true when
a value is less than
b value (and false otherwise).
It is internally implemented on most data types using
Comparable.compareTo() method on the corresponding JVM value.
a | - | first value |
b | - | second value |
(<=) a b is ^k → ^k → boolean,
Returns true when
a value is less than or equal to
b value
(and false otherwise).
It is internally implemented on most data types using
Comparable.compareTo() method on the corresponding JVM value.
a | - | first value |
b | - | second value |
(==) a b is 'l → 'l → boolean,
Returns true when
a and
b values are equal (and false otherwise).
It is internally implemented on most data types using .equals()
method on the corresponding JVM value.
a | - | first value |
b | - | second value |
(>) a b is ^m → ^m → boolean,
Returns true when
a value is greater than
b value (and false otherwise).
It is internally implemented on most data types using
Comparable.compareTo() method on the corresponding JVM value.
a | - | first value |
b | - | second value |
(>=) a b is ^n → ^n → boolean,
Returns true when
a value is greater than or equal to
b value
(and false otherwise).
It is internally implemented on most data types using
Comparable.compareTo() method on the corresponding JVM value.
a | - | first value |
b | - | second value |
and a b is boolean → boolean → boolean,
Logical conjunction of
a and
b.
a | - | first value |
b | - | second value |
not value is boolean → boolean,
Logical negation of the
value.
or a b is boolean → boolean → boolean,
Logical disjunction of
a or
b.
a | - | first value |
b | - | second value |
same? a b is 'dj → 'dj → boolean,
Identity check - returns true when
a and
b reference to the same
object instance (and false otherwise).
a | - | first value reference |
b | - | second value reference |
Notes
It is equivalent to Java == operator (barring primitive values,
which don't exist in Yeti anyway).
Generic collection functions
at collection key is map
<'_r, '_s
> → '_r → '_s,
Array/hash subscription operator
collection[
key] as function.
Returns element at corresponding
key (index).
collection | - | array or hash table |
key | - | array index or hash table key |
Exceptions thrown
NoSuchKey | - | if the key doesn't exist in the given collection |
Examples
numbers = [1: "one", 2: "two", 3: "three"];
println (map (at numbers) [3, 1]); // ["three","one"]
copy collection is ('an
is map
<'_al, '_am
>) → 'an,
Returns a new copy of the given
collection.
collection | - | a list, array or hash map |
delete collection key is map
<'_ar, '_as
> → '_ar → (),
Deletes the index/
key and it's associated value from the
collection. Does nothing if the given
key/index doesn't belong
to the
collection.
collection | - | array or hash map |
key | - | array index or hash map key |
deleteAll collection keylist is map
<'_at, '_au
> → list?
<'_at
> → (),
Deletes from the
collection all keys/indexes (together with their
associated values) existing in the given
keylist.
Keylist
elements that are not
collection keys are ignored.
collection | - | array or hash map |
keylist | - | list of indexes/keys to be removed from the collection |
Examples
a = array ['a', 'b', 'c', 'd', 'e'];
deleteAll a [1, 3];
println a; // outputs ["a","c","e"]
empty? collection is map
<'_aw, '_ax
> → boolean,
Checks whether a
collection is empty, and returns true when it is.
This function works on all kinds of standard collections - lists,
arrays and hashes implement the
map<> interface.
collection | - | collection to check |
in key map is 'bp → map
<'bp, '_bq
> → boolean,
Checks whether a
key exists in the given hash
map or array.
key | - | key value (or array index) to search for |
map | - | hash map or array to be checked |
Examples
h = ['a': 11, 'b': 22];
printKey k =
if k in h then
println "h[\(k)] = \(h[k])"
else
println "\(k) doesn't exist"
fi;
printKey 'b'; // prints h[b] = 22
printKey 'c'; // prints c doesn't exist
length collection is map
<'_by, '_bz
> → number,
Returns count of elements in
collection.
collection | - | a list, array or hash map |
Description
For list or array it's length is returned, and for hash map the number of
key-value pairs in that hash map. The
length function can also be applied
to Java arrays (for example
length new int[10]), as Yeti compiler wraps
these automatically into lists on function arguments.
swapAt map i j is map
<'_dv, '_dw
> → '_dv → '_dv → (),
Swaps two array/hash
map element values stored at indexes
i and
j.
map | - | array or hash table |
i | - | index/key |
j | - | index/key |
Description
The canonical implementation is following:
swapAt map i j =
(tmp = map[i];
map[i] := map[j];
map[j] := tmp);
Array functions
array init is list?
<'q
> → array
<'q
>,
Creates a new array containing elements from the
init list.
init | - | elements in this list will be added into the new array |
Examples
Create an empty array and add some value:
someArray = array [];
push someArray "test";
Create an array containing some given elements:
numbers = array [1..5];
clearArray array is array
<'_x
> → (),
Removes all elements from the
array, leaving it empty.
pop array is array
<'_df
> → '_df,
Pops and returns the last value from the
array, like removing the
top element from stack.
array | - | an array to be popped |
Exceptions thrown
yeti.lang.EmptyArrayException | - | if the array is empty |
push array value is array
<'_dg
> → '_dg → (),
Pushes a
value into the
array behind last element, increasing the
array size by one. Together with the
pop function it allows
treating the
array like a stack.
array | - | an array where to push the value |
value | - | value to be added to the array |
setArrayCapacity array count is array
<'_dk
> → number → (),
Preallocates the
array storage for at least the given element
count,
so pushing elements later would not cause reallocating and coping
the internal storage. Does nothing, if the storage already has
capacity for the required number of elements.
array | - | array where to set the capacity |
count | - | the maximum number of total elements that the array should
be able to store without further reallocations |
shift array is array
<'_dn
> → '_dn,
Shifts the first value off from the
array and returns it, moving all
other elements towards the start.
array | - | an array to be shifted |
Exceptions thrown
yeti.lang.EmptyArrayException | - | if the array is empty |
Notes
The contents of array is not moved internally. Instead of it the
first element is just hidden. This makes the
shift operation O(1) fast,
but leaves the shifted entries internally used (at least until the
internal storage is resized, for example by
push having insufficient
space available).
slice array start end is array
<'_do
> → number → number → array
<'_do
>,
Returns a copy of slice of the given
array, from
start index
to the
end index.
array | - | an array to be used |
start | - | the slice start index (inclusive) in the array |
end | - | the slice end index (exclusive) in the array |
Hash map functions
clearHash map is hash
<'_y, '_z
> → (),
Removes all entries from the hash
map, leaving it empty.
map | - | the hash map to clear |
concurrentHash () is () → hash
<'ag, 'ah
>,
Creates a concurrent hash map (which can be safely used by multiple
threads without synchronizing).
Notes
Implementation uses java.util.concurrent.ConcurrentHashMap.
customHash constructor is (() → ~java.util.Map) → hash
<'ao, 'ap
>,
Creates a hash map backed with some custom implementation
(which instances are created by appling the given
constructor).
constructor | - | a function creating the java.util.Map instance to be used |
forHash hash block is hash
<'_bh, '_bi
> → ('_bh → '_bi → ()) → (),
Iterates over
hash map, calling the
block function for each
hash map entry with key and value as arguments.
hash | - | hash map to iterate |
block | - | function to call |
Examples
Print each hash map key-value pair on separate line.
h = ['test': 54, 'that': 42];
forHash h do k v:
println "\(k): \(v)\n";
done
forJavaMap map block is ~java.util.Map → (~java.lang.Object → ~java.lang.Object → ()) → (),
Iterates over Java
map, calling the
block function for each
map entry with key and value as arguments.
map | - | java.util.Map instance to iterate |
block | - | function to call |
Examples
forJavaMap System#getProperties() do name value:
println {name, value}
done
Prints system properties.
hash list is list?
<'_bk
> → hash
<'_bk, ()
>,
Creates a hash mapping from given
list elements to unit values (you can
think of it being a set). As the hash map is essentially unordered,
the ordering that was present in the given
list will be lost.
list | - | values to use as hash keys |
Examples
hash [11, 22] == [11: (), 22: ()]
identityHash () is () → hash
<'bn, 'bo
>,
Creates an identity hash map, where keys are compared by their
object instance identies (like the
same? function does).
insertHash destination source is hash
<'_bs, '_bt
> → hash
<'_bs, '_bt
> → (),
Inserts all
source map entries to the
destination hash map.
Entries with matching key in both maps will be replaced in
the
destination (with ones from the
source).
destination | - | hash map where to insert the source entries |
source | - | hash map where to take the entries |
Description
The
insertHash function could be implemented with following code:
insertHash destination source =
forHash source do key value:
destination[key] := value
done;
The library implementation uses internally java.util.Map#putAll().
keys hash is hash
<'_bv, '_bw
> → list
<'_bv
>,
Returns list of
hash map keys.
mapHash function hash is ('cj → 'ck → 'cl) → hash
<'cj, 'ck
> → list?
<'cl
>,
Applies the
function to each key-value pair in the given
hash map,
and returns a list of the values returned by these applications.
The order of elements in the returned list is undefined.
function | - | function to apply to the hash map key-value pairs |
hash | - | a hash map |
Examples
mapHash (_ k v = "\(k):\(v)") ['a':1,'b': 3,'c': 5]
May have the following result:
["b:3","c:5","a:1"] is list?<string>
mapIntoHash getKey getValue sequence is ('cm → '_cn) → ('cm → '_co) → list?
<'cm
> → hash
<'_cn, '_co
>,
Creates a new hash map populated with key-value pairs derived
from the
sequence elements by application of
getKey and
getValue
functions.
getKey | - | function to derive hash map key from the sequence element |
getValue | - | function to derive hash map value from the sequence element |
sequence | - | list or array to use for creating the hash map |
Description
The canonical implementation is following:
mapIntoHash getKey getValue sequence =
(result = [:];
for sequence do element:
result[getKey element] := getValue element
done;
result);
setHashDefault hash function is hash
<'_dl, '_dm
> → ('_dl → '_dm) → (),
Sets a given default value
function for the
hash map.
hash | - | hash map |
function | - | default value function |
Description
If non-existing key is requested from the hash map (using []
subscription operator or
at function), the default value
function is applied to the requested key, and the result of
application will be returned as if it had been in the hash map.
If the default value function is not set, the hash maps behave
like having one that throws the NoSuchKeyException. Explicitly
setting it using this (setHashDefault) function overrides this
behaviour.
Examples
Memoization can be implemented using setHashDefault:
fibs = [0: 0, 1: 1];
setHashDefault fibs do x:
res = fibs[x - 1] + fibs[x - 2];
fibs[x] := res;
res
done;
println fibs[100]; // prints 354224848179261915075
This example uses memoization to speed up the naive recursive
fibonacci numbers calculation algorithm (although using a iterative
algorithm would have been even more effective).
weakHash () is () → hash
<'ee, 'ef
>,
Creates a weak hash map, that automatically discards entries
when the key values are garbage collected (and doesn't hold strong
references to the key values).
List and sequence functions
(++) a b is list?
<'b
> → list?
<'b
> → list
<'b
>,
Appends two sequences
a and
b lazily, returns the resulting list.
a | - | first sequence (list or array) |
b | - | second sequence (list or array) |
Description
The list append operator creates a lazy list, which copies
the first sequence on the fly (as elements are requested),
and when it ends, gives the second sequence as the list tail.
If first sequence (a) is an infinite list, then the result is
equivalent to it.
If the second sequence (b) is an array, and is later mutated,
then the resulting list will see the modified array as its tail
(use
copy function to get an independent copy).
Examples
for ([1..4] ++ [13..15]) println;
Prints numbers 1, 2, 3, 4, 13, 14, 15. No list containing those
numbers is never allocated (as lazy ranges are lazily appended).
Notes
The created lazy list head holds references to both concatenated
list heads. When the resulting list is iterated (tail is requested),
the next element from first list is requested using
next() method
on the internal list object (when end of first list is reached, then
the second list is given directly as a tail). This means that left
folding (++) will result in actual Java call stack depth porpotional
to the (++) nesting depth on the left side.
x = tail (((([1] ++ [2]) ++ [3]) ++ [4]) ++ [5]);
In the above example five
++ operators are nested by left side,
resulting call stack depth of 5 for the concatenation (without
parenthesis the ++ operators would associate on the right side).
This can cause problems when deep nesting is created, for example
the following naive implementation of
concat will likely result
in throwing StackOverflowError:
concat = fold (++) [];
concat (map \[1] [1..10000]);
The library implementation of concat doesn't use (++) internally for
this reason.
(:.) value function is 'h → (() → list?
<'h
>) → list
<'h
>,
Constructs a new list from head
value and
function that would return
the tail list. The
function will be applied once, when the list
tail is requested for the first time. This allows creating lazy and
possibly infinite lists or streams.
value | - | value used as new list head |
function | - | function that would return the list tail, when applied
to unit value |
(::) value list is 'i → list?
<'i
> → list
<'i
>,
Constructs a new
list by prepending
value to tail
list.
value | - | value to be prepended |
list | - | list used as tail of the constructed list |
Examples
The following expressions result in equivalent lists.
a :: [b, c] == [a, b, c]
all predicate sequence is ('o → boolean) → list?
<'o
> → boolean,
Returns true, if the
predicate function returns true for
all elements of the given
sequence or the
sequence is empty.
The false value is returned otherwise (
predicate is false
for one or more
sequence elements).
predicate | - | function that returns true or false for sequence element |
sequence | - | list or array to be scanned |
any predicate sequence is ('p → boolean) → list?
<'p
> → boolean,
Returns true if and only if there exists a
sequence element, for which
the
predicate function returns true. A false value is returned otherwise
(empty
sequence or
predicate is false for all
sequence elements).
predicate | - | function that returns true or false for sequence element |
sequence | - | list or array to be scanned |
avoid predicate sequence is ('u → boolean) → list?
<'u
> → 'u,
Returns first element of the
sequence, for which the
predicate
returns false, or the last element, when the
predicate is
true for all elements of the
sequence.
predicate | - | function that returns true for elements to avoid |
sequence | - | sequence of values (array or list) |
Exceptions thrown
java.lang.IllegalArgumentException | - | if the given sequence is empty |
Examples
avoid (== '') [userOpt, systemOpt, defaultOpt]
catSome sequence is list?
<None. 'v |
Some. 'w
> → list
<'w
>,
Returns a lazy list containing values without variant tags from the
Some elements in the given
sequence.
sequence | - | list or array of Some or None variants |
Examples
catSome [Some 3, None (), Some 1, Some 4, None ()] // gives [3, 1, 4]
Notes
The resulting list is created lazily, when consumed, and the sequence
given as argument is lazily consumed as needed for producing the result
list. The order of sequence elements is preserved in the result.
collect generator argument end is ('ab → 'ac) → 'ab → ('ac → boolean) → list
<'ac
>,
Collects values from applications of the
generator function to the
given
argument, until application of the
end predicate to generated
value yields true. The collected values are returned as a list.
generator | - | a function returning a new value on each application |
argument | - | argument to give to the generator function |
end | - | a predicate function, which on application to a generated
value returns true, if no more values should be collected |
Examples
Collect lines from standard input strictly to list:
input = collect readln () ((not) . defined?);
Collect words from string using like pattern match function:
str = 'A lot of weird functions.';
words = collect (like '\w+' str) () empty? |> map head;
println words; // ["A","lot","of","weird","functions"]
concat sequence is list?
<list?
<'ad
>> → list
<'ad
>,
Creates and returns a lazy list concatenating a
sequence of sequences
(flattening it).
sequence | - | a sequence of sequences |
Description
The elements of sequences in the given sequence argument are all concanated
together in the same order. The resulting list is created lazily,
as consumed (and the concat argument is also consumed lazyly, as needed).
The result is affected (and unspecified), when array(s) are given as
concat argument and mutated before consuming the resulting list. A strict
result list or array can be created by applying
copy or
array function
to the lazy list returned by concat (for example (copy . concat)).
Examples
concat [[3..6], [5..7], [4]]
The result is [3, 4, 5, 6, 5, 6, 7, 4].
concatMap function sequence is ('ae → list?
<'af
>) → list?
<'ae
> → list
<'af
>,
Maps a
function over the
sequence and concatenates the results.
Shorthand for (
concat . map function).
function | - | function applied to the sequence elements |
sequence | - | list or array to be processed |
contains? value sequence is 'ak → list?
<'ak
> → boolean,
Returns true if and only if the
sequence contains element equal
to the given
value. If there is no such element, false is returned.
Equality is checked as defined by the (==) operator.
value | - | value to search from the sequence |
sequence | - | list or array to be searched |
drop n sequence is number → list?
<'av
> → list
<'av
>,
Returns the suffix of the
sequence (as list) omitting first
n
sequence elements. An empty list is returned, if
n is equal or
greater than the length of the
sequence.
n | - | how many elements to drop from the start of the sequence |
sequence | - | initial list or array |
Notes
The suffix is returned without copying it. When the
drop function
is used on an array, a list view of the array is returned, consisting
of all elements starting from index n. As the list view still references
to the original array, it will change when the array is modified (use
copy function to get an independent copy).
The
drop function is constant-time operation on lists backed by arrays.
filter predicate sequence is ('az → boolean) → list?
<'az
> → list
<'az
>,
Returns a lazy list containing all those
sequence elements,
for which the
predicate function returns true.
predicate | - | function that returns true or false for sequence element |
sequence | - | list or array to filter |
Examples
filter (_ v = v % 2 == 1) [1..10] // gives odd numbers [1, 3, 5, 7, 9]
Notes
The resulting list is created lazily, when consumed, and the sequence
given as argument is lazily consumed as needed for producing the result
list. The order of sequence elements is preserved in the result.
find predicate sequence is ('ba → boolean) → list?
<'ba
> → list
<'ba
>,
Finds a
sequence element, for which the
predicate function returns true
and returns the
sequence tail starting from that element, or empty list
when the given
predicate isn't true for any list element.
predicate | - | function that returns true for the searched value |
sequence | - | list or array to be searched |
Examples
find (== 3) [1..5] // gives a list [3, 4, 5]
fold function value sequence is ('be → 'bf → 'be) → 'be → list?
<'bf
> → 'be,
Takes
value and first element of the
sequence and applies the given
function to them, then repeats with following
sequence elements, using
the result from previous application as the new
value. Returns the result
of last application (or initial
value when empty
sequence was given).
function | - | two-argument function used for folding |
value | - | initial value |
sequence | - | list or array to fold |
Examples
fold function value [a, b, c]
is equivalent to:
((value `function` a) `function` b) `function` c
Calculate a sum of sequence:
sum l = fold (+) 0 l;
Calculate a factorial:
factorial n = fold (*) 1 [1..n];
The
fold function could be implemented in the following way:
fold function value sequence =
case sequence of
x :: xs: fold function (function value x) xs;
_: value;
esac;
for sequence block is list?
<'bg
> → ('bg → ()) → (),
Iterates over
sequence, applying the
block function to the element
value for each
sequence element.
sequence | - | list or array to iterate |
block | - | function to call |
Examples
Print numbers from 1 to 100, using for on range list.
for [1..100] do i:
println i
done
groupBy predicate sequence is ('bj → 'bj → boolean) → list?
<'bj
> → list
<list
<'bj
>>,
Returns a list of lists, where each sublist contains only equal elements,
and the concatenation of the result is equal to the original
sequence.
Elements are considered equal, when the given
predicate function
is true for them.
predicate | - | function that returns true for values considered equal |
sequence | - | list or array to be processed |
Examples
groupBy (==) [1,1,0,2,0,0,0,3] == [[1,1],[0],[2],[0,0,0],[3]]
head sequence is list?
<'bl
> → 'bl,
Returns the first element of
sequence (which must be non-empty).
sequence | - | the list or array from which to extract the first element |
Exceptions thrown
java.lang.NullPointerException | - | when used on empty list |
yeti.lang.EmptyArrayException | - | when used on empty array |
index value sequence is 'br → list?
<'br
> → number,
Returns 0-based index of the first
sequence element, which equals
to the given
value (using == for equality), or -1 when no element is found.
value | - | value to search for |
sequence | - | list or array to be searched |
Examples
index 'apples' ['oranges', 'apples', 'rats'] // returns 1
iterate first function is ('bu → 'bu) → 'bu → list
<'bu
>,
Returns an infinite lazy list, where each following element is result
of appling the
function to the value of the element before it. The
first element value is given.
first | - | value of the first element in the returned list |
function | - | function to apply to derive the next element value |
Examples
The result of iterate f x is the following infinite list:
[x, f x, f (f x), f (f (f x)), ...]
If addition is used as the function, the result is incrementing sequence:
take 10 (iterate (+1) 0) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list collection is map
<'_ca, '_cb
> → list
<'_cb
>,
Gives values from
collection as a list.
collection | - | a list, array or hash map |
Description
List is returned as is. A list view is returned for an array
(implementation wise just a type cast), so it will change when the
original array is modified. Differently from array, an independent
list consisting of values from the key-value pairs is created and
returned when the collection is a hash map.
Either returned list or collection given as argument should be
explicitly copied (using
copy function), if you want to store the
result for later usage and the original collection might change.
Relying on the mutating list-view of an array is best
to be avoided - having direct reference to the original
collection is more straight-forward solution.
map function sequence is ('cc → 'cd) → list?
<'cc
> → list
<'cd
>,
Returns a list [
function(a),
function(b), ...] for
sequence [a, b, ...]
by applying the
function to each element of the
sequence (either
lazily or strictly).
function | - | function applied to the sequence elements |
sequence | - | list or array to be processed |
Description
A lazy list is returned when applied on normal list. Full result
is not calculated in this case on application, but lazily as the
result is consumed by caller. Arrays and lists backed by arrays
are mapped strictly.
You should ALWAYS use the strict
map' instead, if the mapping function
has side effects, as it's not determined whether the function is applied
by
map on some sequence element when
map was called, some time later
or even never at all (if the result list was not consumed).
map' function sequence is ('ce → 'cf) → list?
<'ce
> → list
<'cf
>,
Returns strict list [
function(a),
function(b), ...] for
sequence
[a, b, ...] by applying the
function to each element of the
sequence.
function | - | function applied to the sequence elements |
sequence | - | list or array to be processed |
Description
It is similar to
map function, but never creates a lazy list.
The
map' is usually faster than
map on lists, unless huge streams
are processed or most of the resulting list is not used. It works
identically to
map on arrays.
map2 function first second is ('cg → 'ch → 'ci) → list?
<'cg
> → list?
<'ch
> → list
<'ci
>,
Returns a lazy list where each element is result of appling the
function
to corresponding elements in the given
first and
second sequences.
Excess elements at the end of longer sequence will be ignored.
function | - | function applied to the sequence elements |
first | - | first list or array to be used |
second | - | second list or array to be used |
Examples
Coupled with the
pair function, two lists could be merged into single
one containing corresponding pairs:
pairs = map2 pair [1..3] ['apple', 'orange', 'cat', 'rock'];
for pairs println;
The second line (
for pairs println;) prints the pairs created
by the
pair function used with
map2:
{fst=1, snd="apple"}
{fst=2, snd="orange"}
{fst=3, snd="cat"}
Notes
The resulting list is created lazily, when consumed, and the sequence
given as argument is lazily consumed as needed for producing the result
list.
mapJavaList function collection is (~java.lang.Object → 'cp) → ~java.util.Collection → list
<'cp
>,
Returns a list of elements obtained by applying the
function
to each element of the Java
collection.
function | - | function applied to list elements |
collection | - | java.util.Collection instance (may be null,
empty list is returned in this case) |
nub sequence is list?
<'_cw
> → list
<'_cw
>,
Returns non-duplicate elements of the
sequence as a list.
This means that no element in the returned list is equal to
some other element (as defined by ==) in this list.
The original ordering of the
sequence is not preserved.
sequence | - | list or array to be processed |
revAppend first second is list?
<'dh
> → list
<'dh
> → list
<'dh
>,
Returns a list consisting of the
first list elements
in reverse order, and with the
second list appended as a tail
(without coping it).
first | - | list or array to be reversed (must be finite) |
second | - | list to be appended to the reversed first sequence |
Examples
revAppend [1..3] [4..6] == [3, 2, 1, 4, 5, 6]
reverse sequence is list?
<'di
> → list
<'di
>,
Returns a list containing the
sequence elements in reverse order.
sequence | - | list or array to be reversed (must be finite) |
Examples
reverse [1..5] == [5, 4, 3, 2, 1]
Notes
Using reverse on range is constant-time operation, as a special
reverse range is returned (instead of creating a list containing
all the range elements).
sort sequence is list?
<^dp
> → list
<^dp
>,
Returns as list the
sequence sorted in ascending order according
to the order defined by the (<) comparision operator.
sequence | - | list or array to be sorted (not modified by sort function) |
Description
The original sequence is copied and sorted using
java.util.Arrays#sort(Object[]) method. The sequence elements
are required to be of ordered type (
^a). The result should be similar
to using
sortBy (<), although the
sort function works usually faster.
Examples
sort [3,1,4,1,5,9,2,6,5,3] == [1,1,2,3,3,4,5,5,6,9]
sortBy compare sequence is ('dq → 'dq → boolean) → list?
<'dq
> → list
<'dq
>,
Returns as list the
sequence sorted according to the
compare function.
The returned list will be ordered in such manner, that
compare x y
returns false for any list elements x and y, where y is before x.
The behaviour of sortBy is undefined, if the
compare function doesn't
define total ordering.
compare | - | function to compare two elements ((<) gives ascending order) |
sequence | - | list or array to be sorted (not modified by sortBy function) |
Examples
sortBy (<) [3,1,4,1,5,9,2,6,5,3] == [1,1,2,3,3,4,5,5,6,9]
Notes
Current implementation uses merge sort algorithm.
Stable sorting is not guaranteed.
splitAt n sequence is number →
list?<'_dr> →
{fst is list
<'_dr
>,
The sequence prefix of length n.
snd is list
<'_dr
>Elements of the sequence starting from the nth element.
}
,
Splits a given
sequence into two parts, returning first
n elements
as
fst and the rest as
snd field. Full
sequence is returned as list
in the
fst field, if
n is equal or greater than the length of the
sequence (and
snd will be empty list in this case).
n | - | position of the split |
sequence | - | list or array to split |
Description
splitAt n sequence = {
fst = take n sequence,
snd = drop n sequence
}
splitBy predicate sequence is ('_ds → boolean) →
list?<'_ds> →
{fst is list
<'_ds
>,
Elements from start of the sequence that
do not satisfy the predicate.
snd is list
<'_ds
>Reminder of the sequence.
}
,
Splits a given
sequence into two parts, putting elements from the start
of the
sequence into fst as long as the
predicate function is false
for a given element. The rest of the
sequence is returned as snd field.
predicate | - | predicate function |
sequence | - | a list or array to split |
sum sequence is list?
<number
> → number,
Returns the arithmetic sum of a finite
sequence of numbers.
Zero is returned for an empty
sequence.
sequence | - | list or array of numbers |
Description
sum = fold (+) 0;
For example, sum [1, 2, 3] is computed as 0 + 1 + 2 + 3.
tail sequence is list?
<'dz
> → list
<'dz
>,
Returns the tail of
sequence consisting of all elements except
the first (head) one. Using tail is equivalent to using drop 1.
sequence | - | the list or array to use |
Notes
The
tail function can be used on array. In this case a list view
of array is returned, consisting of all elements starting from
index 1 (subsequent applications of tail give views with increased
start index). As the list view still references to the original
array, it will change when the array is modified (use
copy function
to get an independent copy).
take n sequence is number → list?
<'ea
> → list
<'ea
>,
Returns first
n elements of the
sequence as a lazy list. All elements
are returned, if
n is equal or greater than the length of the
sequence.
n | - | how many elements to take |
sequence | - | initial list or array |
Notes
The given sequence is lazily consumed as the result returned by take
is consumed. If the sequence is a mutable array, and modified after
appling the
take function, the result of application is undefined.
takeWhile predicate sequence is ('eb → boolean) → list?
<'eb
> → list
<'eb
>,
Returns a lazy list containing longest prefix of the
sequence,
where the
predicate function is true for all elements.
predicate | - | function used to check the sequence elements |
sequence | - | list or array to use |
Notes
The given sequence is lazily consumed as the result returned by
takeWhile is consumed. If the sequence is a mutable array, and
modified after appling the
takeWhile function, the result of
application is undefined.
Numeric functions
(%) dividend divisor is number → number → number,
Remainder of division of the integer part of
dividend
with integer part of
divisor.
dividend | - | the number to divide |
divisor | - | dividend is divided by divisor |
(*) a b is number → number → number,
Arithmetic product of the values
a and
b.
The result may not be accurate when applied to rational numbers
with very big numerator or denominator part as these overflow into
double-precision floating point numbers.
a | - | first number |
b | - | second number |
(+) a b is number → number → number,
Arithmetic sum of the values
a and
b.
The result may not be accurate when applied to rational numbers
with very big numerator or denominator part as these overflow into
double-precision floating point numbers.
a | - | first number |
b | - | second number |
(-) minuend subtrahend is number → number → number,
Substracts
subtrahend from
minuend and returns the difference.
The result may not be accurate when applied to rational numbers
with very big numerator or denominator part as these overflow into
double-precision floating point numbers.
minuend | - | number to substract from |
subtrahend | - | number to substract |
(/) dividend divisor is number → number → number,
Divides
dividend with
divisor and returns the quotient.
The result is rational number, when integer values fitting into
32 bits are divided.
The result may not be accurate when applied to big integers or
rational numbers with very big numerator or denominator part as
these overflow into double-precision floating point numbers.
dividend | - | the number to divide |
divisor | - | dividend is divided by divisor |
abs value is number → number,
Returns the absolute
value of the given numeric
value.
acos value is number → number,
Returns the arc cosine of the given
value in radians.
The returned angle is in the range 0.0..pi.
Implemented using Math#acos(
value).
asin value is number → number,
Returns the arc sine of the given
value in radians.
The returned angle is in the range -pi/2..pi/2.
Implemented using Math#asin(
value).
atan value is number → number,
Returns the arc tangent of the given
value in radians.
The returned angle is in the range -pi/2..pi/2.
Implemented using Math#atan(
value).
b_and a b is number → number → number,
Returns bitwise AND of integer parts of arguments
a and
b.
a | - | first number |
b | - | second number |
b_or a b is number → number → number,
Returns bitwise OR of integer parts of arguments
a and
b.
a | - | first number |
b | - | second number |
cos angle is number → number,
Returns the trigonometric cosine of the given
angle.
Implemented using Math#cos(
angle).
angle | - | an angle in radians |
div dividend divisor is number → number → number,
Divides integer part of
dividend with integer part of
divisor
and returns the integer part of quotient.
dividend | - | the number to divide |
divisor | - | dividend is divided by integer part of divisor |
exp power is number → number,
Returns constant e raised to the given
power.
Implemented using Math#exp(
power).
hex number is number → string,
Returns a hexadecimal string representation of
the integer part of the
number.
number | - | the number to format |
Notes
The following characters are used as digits:
0123456789abcdef
int value is number → number,
Returns the integer part of the given
value.
Notes
Current implementation expects that result fits into
64-bit signed integer (
Long#MIN_VALUE..Long#MAX_VALUE).
ln value is number → number,
Returns natural logaritm (base e) of the given
value.
Implemented using Math#log(
value).
value | - | a positive number (NaN is returned for negative values) |
max a b is ^cr → ^cr → ^cr,
Returns the greater of the two ordered values
a and
b (the ordering is
as defined by the (<) operator). The result is unspecified if one of
the argument values is NaN.
a | - | first value |
b | - | second value |
min a b is ^cv → ^cv → ^cv,
Returns the smaller of the two ordered values
a and
b (the ordering is
as defined by the (<) operator). The result is unspecified if one of
the argument values is floating-point number NaN.
a | - | first value |
b | - | second value |
negate value is number → number,
Returns algebralic negation of argument
value (negate
value = -
value).
number string is string → number,
Converts the given
string into a number and returns the result.
string | - | a string to parse as a number |
Exceptions thrown
java.lang.NumberFormatException | - | when the argument string is not in
a recognized numeric format |
Description
The string argument must be in one of the following formats:
1. Decimal integer of arbitrary size. The result will be
integer number, values not fitting into 64-bit signed integer
are internally stored using the BigInteger class.
2. Octal integer of arbitrary size with
"0o" or
"0O" as prefix.
The result will be integer number.
3. Hexadecimal integer of arbitrary size with
"0x" or
"0X" as prefix.
The result will be integer number.
4. Decimal number with fractional part after dot (for example 17.52).
The result will rational number, if both numerator and denominator
parts of decimal fraction can be expressed as 32-bit signed integers
(exact value). Otherwise the result will be double-precision
floating-point number (possibly inexact value).
5. Decimal number with exponent after 'e' or 'E' (for example 1.23e-3).
Optional fractional part is separated with dot.
The result will be double-precision floating-point number.
6. Decimal number with optional fractional part after dot and 'e' or
'E' at the end (for example 1e). The result will be double-precision
floating-point number. This can be used to force creating a
floating-point number instead of rational or integer number.
This set of formats is identical to the format of numeric literals
in the Yeti source code. Preceding and trailing whitespace characters
are removed before parsing.
pi is number,
Mathematical constant pi (nearest value to pi expressable
as double precision floating point number).
randomInt limit is number → number,
Returns a pseudorandom integer value between 0 (inclusive) and
the given
limit (exclusive). All possible values are produced
with approximately equal probability.
limit | - | the limit on the returned value (must be greater than zero) |
round value is number → number,
Returns the closest integer to the given
value.
Implemented using Math#round(
value).
Notes
Current implementation expects that result fits into
64-bit signed integer (
Long#MIN_VALUE..Long#MAX_VALUE).
shl value count is number → number → number,
Shifts bit representation of integer part of the
value
to left by given
count of bits and returns the result.
value | - | the value to shift |
count | - | how much to shift |
shr value count is number → number → number,
Shifts bit representation of integer part of the
value
to right by given
count of bits and returns the result.
value | - | the value to shift |
count | - | how much to shift |
sin angle is number → number,
Returns the trigonometric sine of the given
angle.
Implemented using Math#sin(
angle).
angle | - | an angle in radians |
sqrt value is number → number,
Returns the positive square root of the given
value.
Implemented using Math#sqrt(
value).
value | - | a positive number or zero (NaN is returned for negative values) |
strOfInt base number is number → number → string,
Returns a string representation of the integer part of
the
number in the given
base.
base | - | the base to use (must be in the range 2 to 36) |
number | - | the number to format |
Exceptions thrown
java.lang.IllegalArgumentException | - | Invalid base argument value |
Notes
The following characters are used as digits:
0123456789abcdefghijklmnopqrstuvwxyz
tan angle is number → number,
Returns the trigonometric tangent of the given
angle.
Implemented using Math#tan(
angle).
angle | - | an angle in radians |
xor a b is number → number → number,
Returns bitwise XOR of integer parts of arguments
a and
b.
a | - | first number |
b | - | second number |
Regular expressions
(!~) haystack regex is string → string → boolean,
Returns true when regular expression has no match in the
haystack string
(and false if it has).
haystack | - | string where to search the given regex match |
regex | - | string representing a regular expression |
Description
This operator is negation of the =~ operator and could be defined in the
following way:
(!~) haystack regex = not (haystack =~ regex)
The regular expression is compiled and matched using the java.util.regex
implementation, and therefore uses the same (Perl regular expression
compatible) syntax. Yeti compiler optimises usage of this operator
when literal string is used as regex argument, so that the regex will
be compiled only once into the java.util.regex.Pattern instance.
Examples
if str !~ '\d' then
println "'\(str)' has no number in it."
fi
(=~) haystack regex is string → string → boolean,
Returns true when regular expression has a match in the
haystack string
(and false otherwise).
haystack | - | string where to search the given regex match |
regex | - | string representing a regular expression |
Description
The regular expression is compiled and matched using the java.util.regex
implementation, and therefore uses the same (Perl regular expression
compatible) syntax. Yeti compiler optimises usage of this operator
when literal string is used as regex argument, so that the regex will
be compiled only once into the java.util.regex.Pattern instance.
Examples
if str =~ '\d' then
println "'\(str)' contains a number in it."
fi
like regex string is string → string → () → array
<string
>,
Returns a function that searches for a
regex match in the given
string.
regex | - | string representing a regular expression |
string | - | string where to search the given regex match |
Description
The returned function attempts to find next substring that matches the
regex pattern, when applied to the unit value (). It returns array of
captured groups from the regex match (including the whole matched substring
as zeroth array element), or empty array, if no match could be found.
The regular expression is compiled and matched using the java.util.regex
implementation, and therefore uses the same (Perl regular expression
compatible) syntax. Yeti compiler optimises usage of this function
when literal string is used as regex argument, so that the regex will
be compiled only once into the java.util.regex.Pattern instance.
Examples
Repeated application of the returned function can be used to find all
substrings matching the regex pattern in the given string:
printMatches matcher =
(match = matcher ();
if not empty? match then
println match[0];
printMatches matcher;
fi);
printMatches (like '\d+' '2012-08-23T04:11Z');
This will print all numbers from the ISO 8601 date:
2012
08
23
04
11
The matches could be collected into list using the
collect function:
matches = collect (like '\d+' '2012-08-23T04:11Z') () empty?);
println matches; // [["2012"], ["08"], ["23"], ["04"], ["11"]]
The returned function can be applied right away,
if only first match is needed:
date = '2012-08-23T04:11Z';
case like '(\d+):(\d+)' date () of
[_, hour, min]: println "Hour: \(hour), minutes: \(min)";
_: println "No time found in the date string.";
esac;
matchAll regex onMatch onText string is string →
(array<string> → 'cq) →
(string → 'cq) →
string →
list<'cq>
,
Generates a lazy list by searching matches of given
regex in the
string.
regex | - | string representation of regular expression |
onMatch | - | function to apply to the captured groups from matches |
onText | - | function to apply to the non-matching substrings |
string | - | string where to search the given regex matches |
Description
When a match is found, the
onText function is applied to the text
between previous match (or start of the string for first match) and
matched substring, if this text isn't zero-length. The
onMatch
function is applied to an array composed of captured groups in the
regex (implicit capture of whole matched substring is given as 0th
element in the capture group array). The
onText function is also
applied to the end of the string after last match found, if the last
match ends before.
The results of
onText and
onMatch applications are added to the
resulting list in the same order as the corresponding substrings were
in the processed string. This
regex match searching and list
construction is done lazily, as the returned list is consumed
(so if you apply
matchAll to long string containing many matches of
the substring and use only head of the result, only the first match
will be actually searched).
The
regex is compiled and matched using the java.util.regex
implementation, and therefore uses the same (Perl regular expression
compatible) syntax. Yeti compiler optimises usage of this function
when literal string is used as regex argument, so that the regex will
be compiled only once into the java.util.regex.Pattern instance.
Examples
for (matchAll '\d+' M T '2012-08-23T04:11Z') println;
Prints the following parts of this ISO 8601 date by matching
number sequences:
M ["2012"]
T "-"
M ["08"]
T "-"
M ["23"]
T "T"
M ["04"]
T ":"
M ["11"]
T "Z"
strSplit regex string is string → string → array
<string
>,
Splits the
string into substrings separated by matches of the
regex,
and returns array of the resulting substrings.
regex | - | string representing a regular expression |
string | - | string to split |
Description
The matches of the regex are used as delimiters, and the substrings
not matching the regex are returned in array in the order they were
in the initial string. Empty substrings before matches are included
in the returned array. Matches at the end of the given string won't
add empty strings to the result.
The regex is compiled and matched using the java.util.regex
implementation, and therefore uses the same (Perl regular expression
compatible) syntax. Yeti compiler optimises usage of this function
when literal string is used as regex argument, so that the regex will
be compiled only once into the java.util.regex.Pattern instance.
Examples
strSplit ';' ';a;foo;;;bar;;' == ["","a","foo","","","bar"]
substAll regex replacement haystack is string → string → string → string,
Returns a copy of the string, with each substring matching the
regex
substituded with the
replacement string in the given
haystack string.
regex | - | string representing a regular expression |
replacement | - | a string to use as replacement |
haystack | - | a original string to process |
Description
Matches of the given regex are searched sequentially from the beginning
of haystack string and replaced with the given replacement string.
The replacement string can contain dollar signs ($) followed by decimal
number (like $1, $2 etc), these will be replaced with text matched by
corresponding group in the regex. $0 will be replaced with whole
matched substring. Backslashes in replacement string escape the
following code unit as a literal code unit (all occurrences of $ and
\ meant to be literal symbols must be escaped this way).
The regex is compiled and matched using the java.util.regex
implementation (Matcher#replaceAll() is used for substitution), and
therefore uses the same (Perl regular expression compatible) syntax.
Yeti compiler optimises usage of this function when literal string is
used as regex argument, so that the regex will be compiled only once
into the java.util.regex.Pattern instance. All strings represent
UTF-16 code unit sequences (internally java.lang.String instances).
Examples
substAll 'a(b*)' '$1' 'an abacus' == 'n bcus'
String functions
(^) a b is string → string → string,
Returns the result of concatenating strings
a and
b.
a | - | first string |
b | - | second string |
Notes
Using this operator is equivalent to the embedded string expression
"\(a)\(b)" except for requiring the arguments to be of string type.
strCapitalize string is string → string,
Returns a copy of the
string, with first character translated to
uppercase. The
string is returned unmodified, if this is not possible.
strChar string index is string → number → string,
Returns one UTF-16 code unit (Java char) from the
string at the given
index.
string | - | an UTF-16 encoded string (internally stored as java.lang.String) |
index | - | a 0-based index of the code unit |
Exceptions thrown
IndexOutOfBoundsException | - | if the index is negative or >= to the length
of string |
strEnds? string suffix is string → string → boolean,
Returns true when the given
string ends with the specified
suffix
(and false otherwise).
string | - | a string value to test |
suffix | - | the expected prefix suffix for the tested string value |
Notes
Compiler optimises
strEnds? applications into
String#endsWith() calls.
strEqIgnoreCase is string → string → boolean,
Compares two strings ignoring case.
strIndexOf string substring from is string → string → number → number,
Finds the start position of the first occurrence of the
substring in
the given
string, that is not before the
from index.
string | - | the string to be searched |
substring | - | the substring to search |
from | - | the search starts from this index |
Exceptions thrown
IndexOutOfBoundsException | - | if the from index is negative or greater
than the length of string |
Notes
The strings are UTF-16 encoded code unit sequences (internally stored as
java.lang.String) with 0-based indexing. Compiler optimises
strIndexOf applications into
String#indexOf() calls.
strJoin separator list is string → list?
<'dt
> → string,
Joins string representations of
list elements into a single string,
with
separator string insterted between each
list element.
The resulting string is returned.
separator | - | a string to be inserted between list elements |
list | - | a list to be joined |
Examples
strJoin '; ' [1..5] == '1; 2; 3; 4; 5'
Notes
The string representations of list elements are idententical to those
that would be returned by the
string function.
strJoin separator (map string list) == strJoin separator list
strLastIndexOf string substring from is string → string → number → number,
Finds the start position of the last occurrence of the
substring in
the given
string, that is not after the
from index.
string | - | the string to be searched |
substring | - | the substring to search |
from | - | the search starts from this index |
Exceptions thrown
IndexOutOfBoundsException | - | if the from index is negative or greater
than the length of string |
Notes
The strings are UTF-16 encoded code unit sequences (internally stored as
java.lang.String) with 0-based indexing. Compiler optimises
strLastIndexOf applications into
String#lastIndexOf() calls.
strLastIndexOf' string substring is string → string → number → number,
Finds the start position of the last occurrence of the
substring in
the given
string.
Same as
strLastIndexOf string substring (strLength string).
string | - | the string to be searched |
substring | - | the substring to search |
Notes
The strings are UTF-16 encoded code unit sequences (internally stored as
java.lang.String) with 0-based indexing, and compiler optimises
strLastIndexOf applications into
String#lastIndexOf() calls.
strLeft string end is string → number → string,
Returns the substring of given
string, from the start of
string
until code unit at
end index. Same as
strSlice string 0 end.
string | - | an UTF-16 encoded string (internally stored as java.lang.String) |
end | - | 0-based index of the code unit ending returned slice (exclusive) |
Exceptions thrown
IndexOutOfBoundsException | - | if the end index is negative or greater
than the length of string |
Notes
The basic multilingual (first) plane of unicode characters are
represented as single code units in UTF-16.
strLeftOf substring string is string → string → string,
Returns the
string prefix until the start of first occurrence of the
specified
substring in the given
string (or undef_str, if the
substring
isn't part of the given
string).
substring | - | the substring to search |
string | - | the string to be searched |
Examples
strLeftOf 'at' 'potatos' == 'pot'
strLength string is string → number,
Returns the length (number of UTF-16 code units) of
string.
string | - | an UTF-16 encoded string (internally stored as java.lang.String) |
Notes
The basic multilingual (first) plane of unicode characters are
represented as single code units in UTF-16, therefore
strLength returns
the count of unicode characters for strings containing only those
characters. The java.lang.String length method works in the same way,
and compiler optimizes
strLength applications into
String#length() calls.
strLower string is string → string,
Returns a copy of the
string, with all uppercase letters translated
to lowercase using the rules of the default locale.
string | - | a string value (internally stored as java.lang.String) |
Notes
Compiler optimizes
strLower applications into
String#toLowerCase() calls.
strPad padding length string is string → number → string → string,
Returns
string with
padding added at the end, if the
string length
is shorter than the desired
length. The
padding is added as many times
as required (but not more) to get result with
length that is not
shorter from the requested one. The original
string is returned
unmodified, if its
length is greater or equal to the requested one.
padding | - | a padding string to append |
length | - | desired result length |
string | - | a string to be padded |
Examples
strPad '.' 10 'test' == 'test......'
strReplace needle replacement haystack is string → string → string → string,
Returns a copy of the string, with all occurences of the
needle
substring replaced with
replacement string in the given
haystack string.
needle | - | a string to search |
replacement | - | a string to use as replacement |
haystack | - | a original string to process |
Description
The needle and replacement strings are treated as literal substring,
with no metacharacters. All strings represent UTF-16 code unit sequences
(internally java.lang.String instances). All occurences of the needle
subsequence starting from beginning of the string are replaced
sequentially and the resulting string is returned.
Examples
strReplace 'aba' '+' 'xabaabababax' == 'x++b+x'
strRight string start is string → number → string,
Returns the substring of given
string, from code unit at
start index
until to the end of
string.
Same as
strSlice string start (strLength string).
string | - | an UTF-16 encoded string (internally stored as java.lang.String) |
start | - | 0-based index of the code unit starting returned slice
(inclusive) |
Exceptions thrown
IndexOutOfBoundsException | - | if the start index is negative or greater
than the length of string |
Notes
The basic multilingual (first) plane of unicode characters are
represented as single code units in UTF-16.
Compiler optimises
strRight applications into
String#substring() calls.
strRightOf substring string is string → string → string,
Returns the
string suffix starting from the end of last occurrence of
the specified
substring in the given
string (or undef_str, if the
substring isn't part of the given
string).
substring | - | the substring to search |
string | - | the string to be searched |
Examples
strRightOf 'at' 'potatos' == 'os'
strSlice string start end is string → number → number → string,
Returns the substring of given
string, from code unit at
start index
until code unit at
end index. The
start and
end indexes are 0-based.
string | - | an UTF-16 encoded string (internally stored as java.lang.String) |
start | - | index of the code unit starting returned slice (inclusive) |
end | - | index of the code unit ending returned slice (exclusive) |
Exceptions thrown
IndexOutOfBoundsException | - | if start or end index is negative or > to
the length of string, or start index is
is greater than the end index |
Notes
The basic multilingual (first) plane of unicode characters are
represented as single code units in UTF-16.
Compiler optimises
strSlice applications into
String#substring() calls.
strStarts? string prefix is string → string → boolean,
Returns true when the given
string starts with the specified
prefix
(and false otherwise).
string | - | a string value to test |
prefix | - | the expected prefix string for the tested string value |
Notes
Compiler optimises
strStarts? applications into
String#startsWith() calls.
strTrim string is string → string,
Returns a copy of the
string, with leading and trailing whitespace
removed.
string | - | a string value (internally stored as java.lang.String) |
Notes
Compiler optimizes
strTrim applications into
String#trim() calls.
The argument instance is directly returned, if there is no whitespace
to remove.
strUncapitalize string is string → string,
Returns a copy of the
string, with first character translated to
lowercase. The
string is returned unmodified, if this is not possible.
strUpper string is string → string,
Returns a copy of the
string, with all lowercase letters translated
to uppercase using the rules of the default locale.
string | - | a string value (internally stored as java.lang.String) |
Notes
Compiler optimizes
strUpper applications into
String#toUpperCase() calls.
string value is 'du → string,
Gives string representation of
value.
Description
String values are returned unmodified. Numbers are formatted into
decimal numbers. Rational and floating-point numbers are formatted
using Double#toString(), which uses dot as decimal separator and
uses scientific exponent notation for very small and big values,
like 1.3E20.
Empty lists and the unit value can be internally represented by JVM
null pointer, which is shown as null. Empty arrays are always shown
as [].
Lists, hash maps, structures and variant values are formatted using
Yeti syntax for them. The values of list/hash elements, structure
fields and variant tag parameters are formatted in the same style
recursively, with an exception for string values and null pointers.
String element/field values are formatted as double-quoted (
"string")
Yeti string literals, and null pointers as [] (because empty list can
be internally a null pointer). Arrays are formatted exactly like lists.
string () // () is null pointer in runtime, result is "null"
string {x = ()} // result is {x=[]}, as here () is a field value
Following the Yeti syntax, lists have comma-separated values
surrounded by [] brackets, for example string list [
"Hello",
"World\n"].
Hash maps are similar, shown as a list of key: value pairs.
Structures are shown as comma-separated list of field=value bindings
surrounded by {} brackets, for example {a=33, s=
"something"}.
The string representation is obtained by calling the Java
String#valueOf(value) method. The library implementation uses
string literal embedded expression:
string value =
"\(value)";
This gets compiled down into the String#valueOf() call (as that
is used by compiler on all embedded string expressions unless
the expression type is already known to be string). The actual
formatting described above is done by #toString() methods in the
internal implementations of those data types.
Examples
num_strs = map string [1..10];
Gets list of numbers 1 to 10 as strings.
parseProperties string is string → hash
<string, string
>,
Parses properties
string given in Java properties file format.
string | - | properties string to parse |
Notes
This requires JDK 1.6 or newer to work.
Miscellaneous functions
(->) object key is {.(->) is 'c → 'd
} → 'c → 'd,
Generic structure-
object reference operator. It gets a
(->) field from
the
object, applies it to the
key argument and returns the result.
object | - | a structure with (->) field |
key | - | name or id of the referenced value |
Description
The implementation is simply the following:
(->) object key =
object.``->`` key;
This means that the
-> operator works with any structure that defines
the
(->) member function. The compiler gives the
-> operator highest
priority (same as structure field reference
(.), and object field
reference
(#)), therefore the
-> with custom-defined meaning can
be easily used in row with those other field reference operators.
(.) f g is ('e → 'f) → ('g → 'e) → 'g → 'f,
Function composition - (
f .
g) x is same as
f (
g x).
Composes unary
f and
g into single function, where
f is
applied to the result of application of
g (to argument).
f | - | first function |
g | - | second function |
Examples
printLength = print . length;
printLength [4,5,6]; // prints 3
This is equivalent to:
printLength x = print (length x);
printLength [4,5,6]; // prints 3
(|>) value function is 'ei → ('ei → 'ej) → 'ej,
Application in reverse order. Expression (
value |> function)
is equivalent to (
function value).
value | - | value given as argument to the function |
function | - | function to apply |
Description
The |> operator can be used to pipe value of expression through multiple
functions. Calls to |> are usually inlined into direct application by Yeti
compiler (if possible). Due to low priority (just above type operators is
and as) the parenthesis around function and argument expressions can be
omitted usually.
Examples
a = iterate (+ 1) 0 |> take 5 |> map (*2);
is same as:
a = map (*2) (take 5 (iterate (+ 1) 0));
both resulting with a = [0,2,4.6,8].
atomic initial is 't →
{compareAndSet expected updated is 't → 't → boolean,
Atomically set the value to the given
updated value,
if the current value is the
expected instance.
expected | - | value expected to be in the reference |
updated | - | a new value to set |
swap updated is 't → 't,
Atomically sets the
updated value and returns the old value.
updated | - | a new value to set |
var value is 't
}
,
Creates a new thread-safe atomic reference with the
initial value set.
initial | - | the initial value for the reference structure value field |
base64Decode data is string → list
<number
>,
Decodes BASE64 encoded
data into byte list and returns the result.
base64Encode bytes is list
<number
> → string,
Encodes list of
bytes as BASE64 string and returns the result.
const x is 'ai → 'aj → 'ai,
K combinator - returns constant function \
x (which returns value
of the (first) argument
x).
x | - | value to be returned by resulting function
(const x () is same as x). |
defined? value is 'aq → boolean,
Checks whether given
value is defined, and returns true when it is.
Undefined values are JVM null pointer, undef_str and undef_bool.
Notes
The unit value () is internally represented by JVM null pointer,
and therefore defined? () is false.
Empty lists are often also considered to be undefined because
of being represented by null pointer (but empty arrays are not).
You should use
empty? to detect empty lists.
failWith message is string → 'ay,
Fail evaluation with given error
message by throwing FailureException.
message | - | error message used as exception description |
Exceptions thrown
flip function x y is ('bb → 'bc → 'bd) → 'bc → 'bb → 'bd,
Applies
function to two arguments in reverse order.
Useful for swapping binary functions arguments.
function | - | function to apply |
x | - | second argument to give to the function |
y | - | first argument to give to the function |
Description
flip function x y = function y x;
The result of applying
flip to binary function is a function that takes
its two arguments in the reverse order of the original function.
Examples
The (>) operator could be defined in the terms of (<) using flip.
(>) = flip (<);
id is 'bm → 'bm,
Identity function (I combinator). The argument value will be
returned as is (id x = x).
lazy promise is (() → '_bx) → () → '_bx,
Memoizes the
promise function with unit argument and returns the
memoized function.
promise | - | a function taking () as argument, used as encapsulation
of an expression |
Description
The application of lazy results in memoized promise, which in essence
is a suspension of lazily evaluated expression. The evaluation can
be forced by applying this memoized promise to unit value (). The result
of evaluation is saved and returned, when it is forced and successfully
evaluated first time, and later applications of the memoized function
will return the saved result.
If the evaluation fails to return a result, throwing an exception
instead, then subsequent attempt to force evaluation by applying the
memoized promise will cause a re-evaluation of the promise function
(by applying it again to the ()).
Successful evaluation of the original promise may happen multiple times,
if done concurrently as a race in multiple threads.
Examples
lazy_sum = lazy \(sum [1..100000000]);
println (lazy_sum ());
println (lazy_sum ());
Here the sum of the large range will be calculated only on the first
application of lazy_sum. The second application returns the result
from first application.
maybe default function option is 'cs → ('ct → 'cs) → (
None. 'cu |
Some. 'ct) → 'cs,
Returns the
default value, when the
option is None _, and
result of applying the
function to the Some parameter value,
when the
option is Some value.
default | - | value to return, when the option argument is None _ |
function | - | function to apply to value,
when the option argument is Some value |
option | - | a variant Some value | None _ |
none is None (),
Short-hand constant for None () value.
nullptr? value is 'cx → boolean,
Check whether given
value is a JVM null pointer, and returns true
when it is.
Notes
Use
defined? instead, unless you really know what you're doing.
The low-level check done by
nullptr? may behave unexpectedly
together with some conversions done by Yeti compiler (for example
nullptr? (System#getenv('???')) is always false).
on f g is ('cy → 'cy → 'cz) →
('da → 'cy) →
'da →
'da →
'cz
,
Binary function composition. Composes binary
f and
unary
g so that arguments to
f are transformed by applying
g.
f | - | binary function |
g | - | unary function used to transform arguments to f |
Description
on f g x y = f (g x) (g y)
Examples
list = [{name="X",v=6},{name="A",v=33}];
sorted = sort (on (<) (.name)) list;
The list is sorted by name structure field.
pair fst snd is 'db → 'dc →
{fst is 'db,
snd is 'dc
},
Constructs a pair structure containing arguments
fst and
snd as fields.
fst | - | first field (fst) to the structure |
snd | - | second field (snd) to the structure |
peekObject value is 'dd →
('de
is Boolean boolean |
Hash hash<'de, 'de> |
List list<'de> |
Number number |
Object ~java.lang.Object |
String string |
Struct {fields is list<string>, value is string → 'de} |
Variant {tag is string, value is 'de}
)
,
Access any
value at runtime. Returns variant tagged with values
runtime type.
The peekObject function may not be always accurate, as full type
information is not available at runtime (for example empty list is
indistinguishable from (), element types of empty collections
remain unknown and function types cannot be determined).
stackTraceString exception is ~java.lang.Throwable → string,
Returns as a formatted string the
exception message and stack trace.
exception | - | an exception to format |
Description
The exception is formatted using the exception#printStackTrace(writer)
method. On most JVM library implementations this results in
a string separated into multiple lines by the
"\n" line feed symbol,
with first line containing the exception name and message, and rest
being method and source file names from the call stack that was active
when the Throwable instance was created.
Examples
java -jar yeti.jar -e "stackTraceString new Exception('TEST')"
java.lang.Exception: TEST
at code.apply(<>:1)
at yeti.lang.compiler.eval._1(eval.yeti:85)
at yeti.lang.compiler.eval.execClass(eval.yeti:63)
at yeti.lang.compiler.eval$evaluateYetiCode$._0(eval.yeti:353)
at yeti.lang.compiler.eval$evaluateYetiCode$.apply(eval.yeti:330)
at yeti.lang.Fun2_.apply(Unknown Source)
at yeti.lang.compiler.yeti.main(yeti.yeti:193)
synchronized monitor block is 'dx → (() → 'dy) → 'dy,
Acquires an intrinsic
monitor lock on behalf of the executing thread,
applies the
block to (), then releases the lock. It is equivalent to
executing the
block in Java synchronized
block.
monitor | - | object that is used for the lock (value of any type can
be use as long as nullptr? monitor is false) |
block | - | function that is applied while the monitor lock is hold |
Exceptions thrown
java.lang.NullPointerException | - | when monitor is a JVM null pointer |
Examples
var nameCount = 0;
var lastName = ''; addName name =
synchronized addName do:
lastName := name;
nameCount := nameCount + 1;
done;
The
addName function is used as a monitor here.
threadLocal initial is (() → '_ec) →
{var value is '_ec,
wipe is () → ()
Clears the thread-local variable.
}
,
Creates a structure with writable property field (
value), that
acts like being an independent instance for each thread accessing it.
initial | - | function returning initial value for
the structures value field (when applied to ()) |
Description
The returned structure has a property field named
value.
Reading the field gives the latest value assigned to it by the same
thread (or the result of appling
initial argument that was given to
the
threadLocal function, if the reading thread has never assigned
another value to the field). Assigning a new value to the field changes
it only for the assigning thread.
The value associated with thread can be removed by calling the
.wipe
function field from the structure. Accessing the value field after that
causes new application of the
initial function.
Notes
Internal implementation uses the java.lang.ThreadLocal class.
throw exception is ~java.lang.Throwable → 'ed,
Throws the given
exception. Equivalent to the Java throw operator.
As the
exception is thrown, the function never returns normally.
exception | - | exception instance to be thrown |
Exceptions thrown
NullPointerException | - | This is thrown if the given exception is
Java null pointer. |
Examples
throw new IllegalArgumentException("Bad example");
utf8 is string,
String constant for the UTF-8 charset ("UTF-8").
withExit block is (('eg → 'eh) → 'eg) → 'eg,
Provides a return function for a
block.
block | - | a function to apply |
Description
Creates a return function and applies the given block to it.
When the return function is applied to some value, it causes the
withExit application to return with this value (stopping the block
execution). The return function may be applied only during the
withExit application. If applied later, an IllegalStateException
is thrown, with message indicating an exit out of scope error.
Examples
The
withExit function can be useful, when early return from some
code is desired.
processItems l =
withExit do return:
for l do v:
if not process v then
return (Bad v)
fi
done;
Ok ()
done;
Notes
The withExit return works internally by throwing and catching a special
Error instance, that for efficiency is constructed without stack trace.
Be careful with lazy lists, for example:
withExit do e: 1 :. \(e []) done
fails with exit out scope error, when the resulting lazy list is used.
yetiRuntimeVersion is string
Yeti version string.
Notes
Don't try simple string comparision on it.
At least convert it to number list with something like:
map number (strSplit '\D+' yetiRuntimeVersion) >= [0,9]