Module std.functional.init
Functional programming.
A selection of higher-order functions to enable a functional style of programming in Lua.
Load this module with require 'std.functional.init'. When
lua-stdlib is installed, require 'std.functional' loads the older,
incompatible 41.x API that it keeps under that name, and only gives you
this module when lua-stdlib is not installed.
Functions that iterate take their data first and their function last,
as table.sort and string.gsub do. The data is an iterable: a
table, whose items are its values from 1 to its n field or length, so
table.pack keeps holes; or an iterator function, whose items end
with its first nil result, such as s:gmatch(pat). Use iter to
pass a stateless iterator, such as iter(pairs(t)). The function is
called with all the results of an iteration. Functions that return
several items return lists, with their length in field n.
Each function documents its calling convention as a Signature, in the
syntax of typecheck declarations: | separates alternative types, ?
marks an argument that may be nil, [...] one that may be left out
even when others follow it, <...> one that may only be left out along
with every argument after it, and ... stands for any number more of
the same. So foldl(table|function, [any], callable) takes an
iterable, optionally an initial value, and a function, and
detect(table|function, <?any>) takes an iterable, and optionally a
predicate.
When an argument in [...] is left out, the arguments after it move up
to take its place, so a nil passed there is a value. An argument in
<...> is the last that is passed, and it can be left out, or be nil,
which are not the same where nil is a value to compare with: some(t)
tests for anything truthy, but some(t, nil) tests for a nil item.
A predicate is a plain function. Anything else that is passed where a
predicate is wanted, a functable such as a lambda included, is a
value to compare each item with, as ==. Use predicate to call a
functable instead.
Iterables and lists
| collect (seq) | Collect the items of an iterable into a list. |
| compact (seq) | Collect the items of an iterable that are not nil. |
| each (seq, fn) | Call a function with each item of an iterable, for its effects. |
| filter (seq, pred) | Filter the items of an iterable with a predicate. |
| flatmap (seq, fn) | Map a function over an iterable, and concatenate the results. |
| flatten (t) | Flatten a nested table into a list. |
| foldl (seq[, acc={}], fn) | Fold a binary function left associatively. |
| foldr (seq[, acc={}], fn) | Fold a binary function right associatively. |
| iter (f[, s[, c]]) | Make an iterator function from a generic-for triple. |
| map (seq, fn) | Map a function over the items of an iterable. |
| map_with (tt, fn) | Map a function over a table of argument lists. |
| partition (seq, pred) | Split the items of an iterable by a predicate. |
| product (...) | Functional list product. |
| reject (seq, pred) | Reject the items of an iterable that pass a predicate. |
| reversed (seq) | The items of an iterable in the opposite order. |
| shape (t, dims) | Shape a table according to a list of dimensions. |
| sorted (seq[, cmp]) | A sorted copy of an iterable. |
| zip (tt) | Zip a table of tables. |
| zip_with (tt, fn) | Zip a list of tables together with a function. |
Searching and predicates
| contains (seq, x) | Whether any item of an iterable matches a value or predicate. |
| detect (seq[, pred]) | Find the first item of an iterable that passes a predicate. |
| firstof (seq[, pred], fn) | The first result of calling a function with each item that passes. |
| indexof (seq[, pred]) | The position of the first item that passes a predicate. |
| isempty (x) | Whether a value is a table with nothing in it. |
| isfile (x, ...) | Whether a value is an open file. |
| islistkey (t, k) | Whether a key is the index of an item of the list part of a table. |
| isnonzero (x, ...) | Whether a value is anything but the number zero. |
| isstring (x, ...) | Whether a value is a string. |
| istable (x, ...) | Whether a value is a table. |
| predicate (x) | Make a predicate from a value, a function or a functable. |
| some (seq[, pred]) | Whether any item of an iterable passes a predicate. |
Tables
| destructure (t) | The key and value of the first entry of a table. |
| except (t, pred) | A copy of a table without the keys that match a key or predicate. |
| invert (t) | Swap the keys and values of a table. |
| keys (t) | The keys of a table. |
| mapkeys (t, fn) | Map a function over the keys of a table. |
| mapvalues (t, fn) | Map a function over the values of a table. |
| merged (...) | A new table with the entries of each of some tables. |
| pluck (t, keys) | A table of just some of the entries of a table. |
| tabulate (seq, fn) | Make a table from the key and value results of a function. |
| values (t) | The values of a table. |
Functions
| any (...) | Call a series of functions until one returns non-nil. |
| apply (fn, argu) | Call a function with the items of a list as its arguments. |
| bind (fn, argt) | Partially apply a function. |
| call (fn, ...) | Call a function with the arguments. |
| callable (x) | Return x if it can be called, otherwise nil. |
| compose (...) | Compose functions. |
| converge (x[, limit=1000], fn) | Call a function with a value, and then with each result, until the result is the same as the value it was called with. |
| curry (fn, n) | Curry a function. |
| force (x, ...) | Call x with the arguments if it can be called, otherwise return it. |
| id (...) | Identity function. |
| iscallable (x) | Whether x can be called. |
| lambda (s) | Compile a lambda string into a Lua function. |
| memoize (fn[, mnemonicfn=std.tostring]) | Memoize a function, by wrapping it in a functable. |
| nop () | No operation. |
Dispatch and selection
| case (with, branches) | A rudimentary case statement. |
| choose (test, consequent[, alternative]) | Select one of two values by a test. |
| cond (...) | A rudimentary condition-case statement. |
| default (x[, d]) | A value, unless it is nil, then a default. |
| either (x[, default]) | A value, unless it is nil or an empty table, then a default. |
Types
| mnemonic (...) | Signature of a memoize argument normalization callback function. |
Iterables and lists
- collect (seq)
-
Collect the items of an iterable into a list.
An iterable is a table, whose items are its values from 1 to its
nfield or its length, or an iterator function, whose items end with its first nil result. Where an iterator function returns several values, the item is the first of them.Signature:
-
collect(table|function)
Parameters:
- seq table or function an iterable
Returns:
-
table
a list of the items, with its length in field
nSee also:
Usage:
--> {'a', 'b', 'c', n=3} collect(('a b c'):gmatch '%a') --> {1, 2, 3, n=3}, the first result of each iteration collect(iter(ipairs {'a', 'b', 'c'}))
- compact (seq)
-
Collect the items of an iterable that are not nil.
Only nil is left out, so
falseis kept, as it is a value. The holes in a table, and the nil elements that flatten keeps, go.Signature:
-
compact(table|function)
Parameters:
Returns:
-
table
a list of the items that are not nil, with its length
in field `n`See also:
Usage:
--> {1, false, 3, n=3} compact(pack(1, nil, false, nil, 3)) --> {1, 2, 3, n=3} compact(flatten(pack(1, nil, pack(2, nil, 3))))
- each (seq, fn)
-
Call a function with each item of an iterable, for its effects.
The function is called with all the results of an iteration, and
every item is visited, whatever it returns. Use some or
firstof to stop early.
Signature:
-
each(table|function, callable)
Parameters:
See also:
Usage:
each(args, function(arg) print(arg) end)
- filter (seq, pred)
-
Filter the items of an iterable with a predicate.
Only a plain function is a predicate; anything else, a functable
included, is a value to compare each item with, as
==. Use predicate to call a functable. The predicate is called with all the results of an iteration, and the item kept is the first of them.Signature:
-
filter(table|function, ?any)
Parameters:
- seq table or function an iterable, see collect
- pred a predicate function, or a value to compare with
Returns:
-
table
a list of the items that pass, with its length in
field `n`See also:
Usage:
--> {2, 4, n=2} filter({1, 2, 3, 4}, function(e) return e % 2 == 0 end)
- flatmap (seq, fn)
-
Map a function over an iterable, and concatenate the results.
fn is called with all the results of an iteration, and returns an
iterable of items, such as a list, or nil for none.
Signature:
-
flatmap(table|function, callable)
Parameters:
- seq table or function an iterable, see collect
- fn function function returning an iterable of the items to add
Returns:
-
table
a list of the items of every result, in order, with
its length in field `n`See also:
Usage:
--> {1, 1, 2, 2, n=4} flatmap({1, 2}, function(e) return {e, e} end)
- flatten (t)
-
Flatten a nested table into a list.
Signature:
-
flatten(table)
Parameters:
- t table a table
Returns:
-
table
a list of all non-table elements of t, in order,
with its length in field `n`; a hole in a table is an element that is nil, so it is keptSee also:
Usage:
--> {1, 2, 3, 4, 5} flatten {{1, {{2}, 3}, 4}, 5} --> {1, 2, 3, n=3}, leaving out the elements that are nil compact(flatten(pack(1, nil, pack(2, nil, 3))))
- foldl (seq[, acc={}], fn)
-
Fold a binary function left associatively.
Call fn with the accumulator and all the results of each
iteration, from the left. If fn returns nil, the accumulator is
left as it was.
Signature:
-
foldl(table|function, [any], callable)
Parameters:
- seq table or function an iterable, see collect
- acc initial accumulator (default {})
- fn function binary function
Returns:
-
the final accumulator
See also:
Usage:
foldl({10000, 100, 10}, 1000000, operator.quot) == ((1000000 / 10000) / 100) / 10
- foldr (seq[, acc={}], fn)
-
Fold a binary function right associatively.
Call fn with each item and the accumulator, from the right. An
iterator function is collected into a list first, and so only its
first result of each iteration is passed on. If fn returns nil,
the accumulator is left as it was.
Signature:
-
foldr(table|function, [any], callable)
Parameters:
- seq table or function an iterable, see collect
- acc initial accumulator (default {})
- fn function binary function
Returns:
-
the final accumulator
See also:
Usage:
foldr({10000, 100}, 10, operator.quot) == 10000 / (100 / 10)
- iter (f[, s[, c]])
-
Make an iterator function from a generic-for triple.
Each call passes on all of the results of the next iteration, and
they are nil once the iterator is exhausted. Use it to pass a
stateless iterator, such as
pairs(t), where an iterator function is wanted.Signature:
-
iter(callable, )
Parameters:
- f
function
iterator function, as in a generic
for - s invariant state, passed to f on every call (optional)
- c initial control variable (optional)
Returns:
-
function
an iterator function with s and c closed over
Usage:
--> {'a', 1}, {'b', 2} local next_pair = iter(pairs {a=1, b=2})
- f
function
iterator function, as in a generic
- map (seq, fn)
-
Map a function over the items of an iterable.
The function is called with all the results of an iteration.
Signature:
-
map(table|function, callable)
Parameters:
Returns:
-
table
a list of the first result of fn for each item,
holes kept, with its length in field `n`See also:
Usage:
--> {1, 4, 9, 16, n=4} map({1, 2, 3, 4}, lambda '=_1*_1')
- map_with (tt, fn)
-
Map a function over a table of argument lists.
Signature:
-
map_with(table of tables, callable)
Parameters:
- tt table a table of fn argument lists
- fn function map function
Returns:
-
table
new table of fn results
See also:
Usage:
--> {'123', '45'}, {a='123', b='45'} conc = bind(map_with, {[2] = lambda '|...|table.concat {...}'}) conc {{1, 2, 3}, {4, 5}}, conc {a={1, 2, 3, x='y'}, b={4, 5, z=6}}
- partition (seq, pred)
-
Split the items of an iterable by a predicate.
Signature:
-
partition(table|function, ?any)
Parameters:
- seq table or function an iterable, see collect
- pred a predicate function, or a value to compare with
Returns:
-
table
a list of the items that pass, with its length in
field `n` - table a list of the items that fail, likewise
See also:
Usage:
--> {2, 4, n=2}, {1, 3, n=2} partition({1, 2, 3, 4}, function(e) return e % 2 == 0 end)
- product (...)
-
Functional list product.
Return a list of each combination possible by taking a single element from each of the argument lists.
Signature:
-
product(list...)
Parameters:
- ... operands
Returns:
-
result
Usage:
--> {'000', '001', '010', '011', '100', '101', '110', '111'} map(product({0,1}, {0, 1}, {0, 1}), table.concat)
- reject (seq, pred)
-
Reject the items of an iterable that pass a predicate.
The opposite of filter.
Signature:
-
reject(table|function, ?any)
Parameters:
- seq table or function an iterable, see collect
- pred a predicate function, or a value to compare with
Returns:
-
table
a list of the items that fail, with its length in
field `n`See also:
Usage:
--> {1, 3, n=2} reject({1, 2, 3, 4}, function(e) return e % 2 == 0 end)
- reversed (seq)
-
The items of an iterable in the opposite order.
Unlike
ipairs, this keeps the holes in a table, so the position of each item is as far from the end as it was from the start.Signature:
-
reversed(table|function)
Parameters:
Returns:
-
table
a new list of the items in reverse order, with its
length in field `n`Usage:
--> {'c', 'b', 'a', n=3} reversed {'a', 'b', 'c'}
- shape (t, dims)
-
Shape a table according to a list of dimensions.
Dimensions are given outermost first and items from the original list are distributed breadth first; there may be one 0 indicating an indefinite number. Hence,
{0}is a flat list,{1}is a singleton,{2, 0}is a list of two lists, and{0, 2}is a list of pairs.Algorithm: turn shape into all positive numbers, calculating the zero if necessary and making sure there is at most one; recursively walk the shape, adding empty tables until the bottom level is reached at which point add table items instead, using a counter to walk the flattened original list.
Signature:
-
shape(table, table)
Parameters:
Returns:
-
reshaped list
Usage:
--> {{'a', 'b'}, {'c', 'd'}, {'e', 'f'}} shape({'a', 'b', 'c', 'd', 'e', 'f'}, {3, 2})
- sorted (seq[, cmp])
-
A sorted copy of an iterable.
The sort is stable: items that neither is ordered before the other
keep the order they had.
Signature:
-
sorted(table|function, )
Parameters:
- seq table or function an iterable, see collect
- cmp
function
function to call with two items, returning
trueif
(optional)the first is ordered before the second; by default `<`
Returns:
-
table
a new list of the items in order, with its length in
field `n`Usage:
--> {1, 2, 3, n=3} sorted {3, 1, 2}
- zip (tt)
-
Zip a table of tables.
Make a new table, with lists of elements at the same index in the
original table. This function is effectively its own inverse.
Signature:
-
zip(table of tables)
Parameters:
- tt table a table of tables
Returns:
-
table
new table with lists of elements of the same key
from *tt*See also:
Usage:
--> {{1, 3, 5}, {2, 4}}, {a={x=1, y=3, z=5}, b={x=2, y=4}} zip {{1, 2}, {3, 4}, {5}}, zip {x={a=1, b=2}, y={a=3, b=4}, z={a=5}}
- zip_with (tt, fn)
-
Zip a list of tables together with a function.
Signature:
-
zip_with(table of tables, callable)
Parameters:
- tt table table of tables
- fn function function
Returns:
-
table
a new table of results from calls to fn with arguments
made from all elements the same key in the original tables; effectively the 'columns' in a simple listof lists.
See also:
Usage:
--> {'135', '24'}, {a='1', b='25'} conc = bind(zip_with, {[2] = lambda '|...|table.concat {...}'}) conc {{1, 2}, {3, 4}, {5}}, conc {{a=1, b=2}, x={a=3, b=4}, {b=5}}
Searching and predicates
- contains (seq, x)
-
Whether any item of an iterable matches a value or predicate.
Anything but a plain function is compared with each item, as
==, socontains(t, nil)asks whether t has a hole. Use predicate to call a functable. Deep equality isbind(operator.eqv, {x}).Signature:
-
contains(table|function, ?any)
Parameters:
Returns:
-
boolean
trueif any item matches, otherwisefalseSee also:
Usage:
--> true contains({'a', 'b', 'c'}, 'b')
- detect (seq[, pred])
-
Find the first item of an iterable that passes a predicate.
The predicate is called with all the results of an iteration. If
pred is omitted, it passes anything truthy, as in some:
use
detect(seq, false)to findfalse. An explicitnil, unlike leaving pred out, is compared with the items, as for contains.Signature:
-
detect(table|function, )
Parameters:
- seq table or function an iterable, see collect
- pred a predicate function, or a value to compare with (optional)
Returns:
-
the first item that passes, or
nilif there isn't oneSee also:
Usage:
--> 'b' detect({'a', 'b', 'c'}, function(e) return e > 'a' end)
- firstof (seq[, pred], fn)
-
The first result of calling a function with each item that passes.
fn is called with all the results of an iteration, and the
predicate with all the results of that call. The call, and so the
iteration, stops at the first call that passes, and its first result
is returned, so fn is not called for items after it. If pred is
omitted, it passes anything truthy.
An explicit
nilfor pred, unlike leaving it out, is compared with the results.Signature:
-
firstof(table|function, [?any], callable)
Parameters:
- seq table or function an iterable, see collect
- pred a predicate function, or a value to compare with (optional)
- fn function function to call with each item
Returns:
the first result of the first call of fn that passes, or
`nil` if there isn't oneSee also:
Usage:
--> 'two': parse is not called for items after 2 firstof({1, 2, 3}, function(e) if e == 2 then return 'two' end end) --> the first file that opens firstof(paths, io.open)
- indexof (seq[, pred])
-
The position of the first item that passes a predicate.
The predicate is called with all the results of an iteration. If
pred is omitted, it passes anything truthy, and anything
that is not a function is compared with each item, as
==. An explicitnil, unlike leaving pred out, is compared with the items, as for contains.Signature:
-
indexof(table|function, )
Parameters:
- seq table or function an iterable, see collect
- pred a predicate function, or a value to compare with (optional)
Returns:
-
int or nil
the position of the first item that passes, or
`nil` if there isn't oneSee also:
Usage:
--> 2 indexof({'a', 'b', 'c'}, 'b')
- isempty (x)
-
Whether a value is a table with nothing in it.
A table with only an
nfield of 0 is empty too, as the list results of this module are.Signature:
-
isempty(?any)
Parameters:
- x a value
Returns:
-
boolean
trueif x is an empty table, otherwisefalseSee also:
Usage:
--> true, true, false isempty {}, isempty(table.pack()), isempty ''
- isfile (x, ...)
-
Whether a value is an open file.
A file that has been closed is not.
Signature:
-
isfile()
Parameters:
- x a value
- ...
ignored, so that it can test the first result of an
iteration that has several
Returns:
-
boolean
trueif x is an open file, otherwisefalseUsage:
--> true, false, false isfile(io.stdout), isfile 'stdout', isfile(nil)
- islistkey (t, k)
-
Whether a key is the index of an item of the list part of a table.
A list has the items from 1 to its
nfield, or its length, so a key is a list key only if it is an integer in that range:nitself, and the keys of the fields that are not items, are not.Signature:
-
islistkey(table, ?any)
Parameters:
- t table a table
- k a key
Returns:
-
boolean
trueif k indexes an item of t, otherwise`false`See also:
Usage:
--> true, false, false islistkey({'a', b=1}, 1), islistkey({'a', b=1}, 'b'), islistkey({'a'}, 2)
- isnonzero (x, ...)
-
Whether a value is anything but the number zero.
Handy for exit statuses:
firstof(steps, isnonzero, call)is the first failure of a series of steps.Signature:
-
isnonzero()
Parameters:
- x a value
- ...
ignored, so that it can test the first result of an
iteration that has several
Returns:
-
boolean
falseif x is the number0, otherwisetrueSee also:
Usage:
--> false, true, true isnonzero(0), isnonzero(1), isnonzero(nil)
- isstring (x, ...)
-
Whether a value is a string.
Signature:
-
isstring()
Parameters:
- x a value
- ...
ignored, so that it can test the first result of an
iteration that has several
Returns:
-
boolean
trueif x is a string, otherwisefalseSee also:
Usage:
--> {'a', 'b'} filter({'a', 1, 'b'}, isstring)
- istable (x, ...)
-
Whether a value is a table.
A table with a metatable is a table too, whatever its type name.
Signature:
-
istable()
Parameters:
- x a value
- ...
ignored, so that it can test the first result of an
iteration that has several
Returns:
-
boolean
trueif x is a table, otherwisefalseSee also:
Usage:
--> {{1}, {2}} filter({{1}, 'x', {2}}, istable)
- predicate (x)
-
Make a predicate from a value, a function or a functable.
A plain function is returned as is, and a lambda is unwrapped to
the function inside it, so that its source string can no longer be
recovered. Any other callable is wrapped in a plain function that
calls it, since it may use its own table when it is called.
Anything else becomes a test for equality (as
==, so honouring__eq) with it, includingnil.Functions that take a predicate, or a value to test for, treat a plain function as the predicate and everything else, a functable included, as a value, because functables in a sequence are usually data: a std.prototype object, for example, is callable. Pass
predicate(functable)to use a functable as the predicate instead, and to search for a function value, usebind(operator.eq, {f}). For deep equality usebind(operator.eqv, {x}).Signature:
-
predicate(?any)
Parameters:
- x a value, a function that tests a value, or a functable
Returns:
-
function
a predicate for x
Usage:
is_five = predicate(5) is_five(5), is_five(6) --> true, false is_even = predicate(lambda '|e| e % 2 == 0')
- some (seq[, pred])
-
Whether any item of an iterable passes a predicate.
If pred is omitted, it passes anything truthy.
An explicit
nil, unlike leaving pred out, is compared with the items, as for contains.Signature:
-
some(table|function, )
Parameters:
- seq table or function an iterable, see collect
- pred a predicate function, or a value to compare with (optional)
Returns:
-
boolean
trueif any item passes, otherwisefalseSee also:
Usage:
--> true some({false, 'x'})
Tables
- destructure (t)
-
The key and value of the first entry of a table.
This is
next(t), named for taking apart a table of one pair, as the items of a list of one-pair tables are: any other table has no first entry that you can rely on.Signature:
-
destructure(table)
Parameters:
- t table a table of one pair
Returns:
-
the key of the entry, or
nilif t is empty - the value of the entry
Usage:
--> 'name', 'value' destructure {name='value'}
- except (t, pred)
-
A copy of a table without the keys that match a key or predicate.
Anything but a plain function is compared with each key, as
==. Use pluck to keep keys instead.Signature:
-
except(table, ?any)
Parameters:
- t table a table
- pred
a predicate function to call with each key, or a key
to compare with
Returns:
-
table
a new table of the entries of t for the keys that
do not match, which is empty if there are noneSee also:
Usage:
--> {b=2, c=3} except({a=1, b=2, c=3}, 'a')
- invert (t)
-
Swap the keys and values of a table.
If more than one key has the same value, one of them wins.
Signature:
-
invert(table)
Parameters:
- t table a table
Returns:
-
table
a new table with the values of t for keys, and its
keys for valuesSee also:
Usage:
--> {a=1, b=2} invert {'a', 'b'}
- keys (t)
-
The keys of a table.
The keys are in a fixed order, so that the same table always gives
the same list: numbers first, in numeric order, and then all the
others by their string form, as
strin std.normalize renders the keys of a table. values lists the values in the same order. Every field has a key, so thenfield of a list with a length is one too: use collect to list the items of a list.Signature:
-
keys(table)
Parameters:
- t table a table
Returns:
-
table
a list of the keys of t, with its length in
field `n`See also:
Usage:
--> {1, 2, 'a', 'b', n=4} keys {a=1, 'x', 'y', b=2}
- mapkeys (t, fn)
-
Map a function over the keys of a table.
The values are kept. If fn returns nil for a key, the entry is
left out, and if it returns the same key for more than one, one of
them wins.
Signature:
-
mapkeys(table, callable)
Parameters:
- t table a table
- fn function map function, called with each key
Returns:
-
table
a new table of the values of t for the results of
*fn*See also:
Usage:
--> {A=1, B=2} mapkeys({a=1, b=2}, string.upper)
- mapvalues (t, fn)
-
Map a function over the values of a table.
Keys are kept. The result of fn is stored as it is, so a value can
map to
false; return the value itself to pass it through, and return nil to leave the key out of the result.Signature:
-
mapvalues(table, callable)
Parameters:
- t table a table
- fn function map function, called with each value
Returns:
-
table
a new table of the same keys, and the results of fn
See also:
Usage:
--> {a=2, b=4} mapvalues({a=1, b=2}, lambda '=_1 * 2')
- merged (...)
-
A new table with the entries of each of some tables.
Where tables have a key in common, the last of them with it wins,
even if its value is
false. A nil argument is skipped. Only the entries of each table are copied, not its metatable, and not the tables that they hold.Signature:
-
merged()
Parameters:
- ... table tables to merge
Returns:
-
table
a new table of the entries of ...
See also:
Usage:
--> {a=1, b=3, c=4} merged({a=1, b=2}, {b=3, c=4}) defaults = {color='red'} options = merged(defaults, user_options)
- pluck (t, keys)
-
A table of just some of the entries of a table.
Signature:
-
pluck(table, table|function)
Parameters:
Returns:
-
table
a new table of the entries of t for those keys,
leaving out any that are nil, which is empty if there are noneSee also:
Usage:
--> {a=1, c=3} pluck({a=1, b=2, c=3}, {'a', 'c', 'd'})
- tabulate (seq, fn)
-
Make a table from the key and value results of a function.
Items for which fn returns a nil key are left out, and a later
result for a key replaces an earlier one.
Signature:
-
tabulate(table|function, callable)
Parameters:
- seq table or function an iterable, see collect
- fn
function
function called with all the results of an iteration, to
return a key and a value
Returns:
-
table
a table of the keys and values from fn
See also:
Usage:
--> {a=1, b=2} tabulate(iter(pairs {1, 2}), function(i, v) return ({'a', 'b'})[i], v end)
- values (t)
-
The values of a table.
Like
table.keysin std.normalize, the order is not specified, and every field is a value, so thenfield of a list with a length is one too: use collect to list the items of a list.Signature:
-
values(table)
Parameters:
- t table a table
Returns:
-
table
a list of the values of t, with its length in
field `n`See also:
Usage:
--> {'x', 'y', 1, 2, n=4} values {a=1, 'x', 'y', b=2}
Functions
- any (...)
-
Call a series of functions until one returns non-nil.
Signature:
-
any(callable...)
Parameters:
- ... function functions to call
Returns:
-
function
to call fn1 .. fnN until one returns non-nil.
Usage:
old_object_type = any(std.object.type, io.type, type)
- apply (fn, argu)
-
Call a function with the items of a list as its arguments.
The items of argu are its values from 1 to its
nfield or its length, so a list made withtable.packkeeps its trailing nils.Signature:
-
apply(callable, table)
Parameters:
- fn function function to call
- argu table list of arguments for fn
Returns:
-
the results of calling fn
See also:
Usage:
apply(math.max, {3, 9, 4}) --> 9
- bind (fn, argt)
-
Partially apply a function.
Signature:
-
bind(callable, table)
Parameters:
- fn function function to apply partially
- argt table table of fn arguments to bind
Returns:
-
function with argt arguments already bound
Usage:
cube = bind(std.functional.operator.pow, {[2] = 3})
- call (fn, ...)
-
Call a function with the arguments.
Unlike force, this is an error if fn cannot be called.
Signature:
-
call(callable, )
Parameters:
- fn function function to call
- ... arguments for fn
Returns:
-
the results of calling fn
See also:
Usage:
call(string.rep, 'ab', 3) --> 'ababab'
- callable (x)
-
Return x if it can be called, otherwise
nil. A function can be called, and so can a functable, a table with a__callmetamethod. The functable itself is returned, rather than its__callmetamethod, which needs the functable as its first argument; this is the same function as std.normalize's.Signature:
-
callable()
Parameters:
- x an object or primitive
Returns:
-
x if x can be called, otherwise
nilSee also:
Usage:
(callable(functable) or function() end)(args)
- compose (...)
-
Compose functions.
Signature:
-
compose(callable...)
Parameters:
- ... function functions to compose
Returns:
-
function
composition of fnN .. fn1: note that this is the
reverse of what you might expect, but means that code like:
compose(function(x) return f(x) end, function(x) return g(x) end))can be read from top to bottom.
Usage:
vpairs = compose(table.invert, ipairs) for v, i in vpairs {'a', 'b', 'c'} do process(v, i) end
- converge (x[, limit=1000], fn)
-
Call a function with a value, and then with each result, until the
result is the same as the value it was called with.
Signature:
-
converge(?any, [int], callable)
Parameters:
- x a value
- limit integer most calls of fn to make (default 1000)
- fn function function to call with x, and with each result
Returns:
-
the first value that fn returns unchanged
Raises:
errorno convergence after N callsif fn still changes its result after limit callsUsage:
--> 'a' converge('aaa', function(s) return (s:gsub('aa', 'a')) end)
- curry (fn, n)
-
Curry a function.
Signature:
-
curry(callable, int)
Parameters:
- fn function function to curry
- n integer number of arguments
Returns:
-
function
curried version of fn
Usage:
add = curry(function(x, y) return x + y end, 2) incr, decr = add(1), add(-1)
- force (x, ...)
-
Call x with the arguments if it can be called, otherwise return it.
A function or a functable is called, and anything else,
nilandfalseincluded, is returned as it is. This is how case, choose and cond treat their branches, so a branch that is a function is only called when it is selected, and any other value can be a branch too. Use call to insist on a function.Signature:
-
force(?any, )
Parameters:
- x a function, a functable or any other value
- ... arguments for x, if it can be called
Returns:
-
the results of calling x, or x itself
See also:
Usage:
force(function(n) return n + 1 end, 1) --> 2 force('default', 1) --> 'default'
- id (...)
-
Identity function.
Signature:
-
id()
Parameters:
- ... arguments
Returns:
-
arguments
- iscallable (x)
-
Whether x can be called.
Signature:
-
iscallable()
Parameters:
- x an object or primitive
Returns:
-
boolean
trueif x is a function or a functable,otherwise `false`See also:
Usage:
if iscallable(handler) then handler(event) end
- lambda (s)
-
Compile a lambda string into a Lua function.
A valid lambda string takes one of the following forms:
1. `'=expression'`: equivalent to `function(...) return expression end` 1. `'|args|expression'`: equivalent to `function(args) return expression end`The first form (starting with
'=') automatically assigns the first nine arguments to parameters'_1'through'_9'for use within the expression body. The parameter'_1'is aliased to'_', and if the first non-whitespace of the whole expression is'_', then the leading'='can be omitted.The results are memoized, so recompiling a previously compiled lambda string is extremely fast.
Signature:
-
lambda(string)
Parameters:
- s string a lambda string
Returns:
-
functable
compiled lambda string, can be called like a function
Usage:
-- The following are equivalent: lambda '= _1 < _2' lambda '|a,b| a<b'
- memoize (fn[, mnemonicfn=std.tostring])
-
Memoize a function, by wrapping it in a functable.
To ensure that memoize always returns the same results for the same arguments, it passes arguments to fn. You can specify a more sophisticated function if memoize should handle complicated argument equivalencies.
Signature:
-
memoize(callable, )
Parameters:
- fn function pure function: a function with no side effects
- mnemonicfn mnemonic how to remember the arguments (default std.tostring)
Returns:
-
functable
memoized function
Usage:
local fast = memoize(function(...) --[[ slow code ]] end)
- nop ()
-
No operation.
This function ignores all arguments, and returns no values.
Signature:
-
nop()
See also:
Usage:
if unsupported then vtable['memrmem'] = nop end
Dispatch and selection
- case (with, branches)
-
A rudimentary case statement.
Select a branch by matching with against branches: first as a
key, then, if with is a string, against the patterns of the
{pattern, branch}pairs in the array part of branches, in order, and last,branches.default. A key counts if its branch is not nil, so a branch can befalse. A pattern is anchored at both ends, and its captures, or the whole match if it has none, are passed to its branch. Integer keys share the array part with the pattern pairs, so don't use both in one table.Signature:
-
case(?any, table)
Parameters:
- with expression to match
- branches table map possible matches to branches
Returns:
the branch selected, or if it is a function or functable,
the result of calling it with *with* (or the captures of a matching pattern); otherwise `nil`See also:
Usage:
return case(type(object), { table = 'table', string = function() return 'string' end, default = function(s) error('unhandled type: ' .. s) end, }) case(arg, { {'%-%-(%w+)=(.*)', function(name, value) opts[name] = value end}, {'%-(%w)', function(flag) opts[flag] = true end}, default = function(s) files[#files + 1] = s end, })
- choose (test, consequent[, alternative])
-
Select one of two values by a test.
Like
test and consequent or alternative, except that either can befalseornil. A function or functable leg is called with test, and its result returned, but only if it is the one chosen, so pass anything with a side effect, or that is expensive or unsafe to compute, as a function. To return a function itself, wrap it in one.Signature:
-
choose(?any, ?any, )
Parameters:
- test a value, 'truthy' or 'falsey'
- consequent chosen if test is truthy
- alternative chosen if it is not (optional)
Returns:
-
consequent or alternative, or the result of calling it
See also:
Usage:
--> 'yes' choose(1 < 2, 'yes', 'no') --> nothing is read unless the file is wanted choose(wanted, function() return io.open(path):read('a') end)
- cond (...)
-
A rudimentary condition-case statement.
Each clause is a
{test, branch}pair, and the first clause whose test is 'truthy' selects its branch, as an if/elseif chain does; use atruetest for the last clause to make it the default. A test can be nil, which is 'falsey' like any other.Signature:
-
cond(
) Parameters:
- ...
table
clauses
{test, branch}pairs
Returns:
the branch of the first clause that passes, or if it is a
function or functable, the result of calling it with the *test*; otherwise `nil`See also:
Usage:
-- recursively calculate the nth triangular number function triangle(n) return cond( {n <= 0, 0}, {n == 1, 1}, {true, function() return n + triangle(n - 1) end}) end
- ...
table
clauses
- default (x[, d])
-
A value, unless it is nil, then a default.
Only nil is missing, so
false,0, an empty string or table, and a functable such as a lambda, which is an empty table, are all values that x can be. Use it for an optional argument. Unlikeeither, which is for a result that can be empty, an empty table is something.Signature:
-
default(?any, )
Parameters:
- x a value
- d what to return if x is nil (optional)
Returns:
-
x, or d
Usage:
cmp = default(cmp, function(a, b) return a < b end)
- either (x[, default])
-
A value, unless it is nil or an empty table, then a default.
Unlike
x or default, an empty table counts as nothing, andfalseis a value like any other.Signature:
-
either(?any, )
Parameters:
- x a value
- default what to return if x is nil or empty (optional)
Returns:
-
x, or default
See also:
Usage:
--> {'unix'} either({}, {'unix'})