Module functional

Functional programming.

A selection of higher-order functions to enable a functional style of programming in Lua.

Functions

any (...) Call a series of functions until one returns non-nil.
bind (fn, argt) Partially apply a function.
callable (x) Identify callable types.
case (with, branches) A rudimentary case statement.
collect ([ifn=std.npairs], ...) Collect the results of an iterator.
compose (...) Compose functions.
cond (expr, branch, ...) A rudimentary condition-case statement.
curry (fn, n) Curry a function.
filter (pfn[, ifn=std.pairs], ...) Filter an iterator with a predicate.
flatten (t) Flatten a nested table into a list.
foldl (fn[, d=t[1]], t) Fold a binary function left associatively.
foldr (fn[, d=t[1]], t) Fold a binary function right associatively.
id (...) Identity function.
ireverse (t) Return a new sequence with element order reversed.
lambda (s) Compile a lambda string into a Lua function.
map (fn[, ifn=std.pairs], ...) Map a function over an iterator.
map_with (fn, tt) Map a function over a table of argument lists.
memoize (fn[, mnemonicfn=std.tostring]) Memoize a function, by wrapping it in a functable.
nop () No operation.
product (...) Functional list product.
reduce (fn, d[, ifn=std.pairs], ...) Fold a binary function into an iterator.
shape (dims, t) Shape a table according to a list of dimensions.
zip (tt) Zip a table of tables.
zip_with (fn, tt) Zip a list of tables together with a function.

Types

mnemonic (...) Signature of a memoize argument normalization callback function.
predicate (...) Signature of a filter predicate callback function.


Functions

any (...)
Call a series of functions until one returns non-nil.

Parameters:

  • ... func 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)
bind (fn, argt)
Partially apply a function.

Parameters:

  • fn func function to apply partially
  • argt table table of fn arguments to bind

Returns:

    function with argt arguments already bound

Usage:

    cube = bind (functional.operator.pow, {[2] = 3})
callable (x)
Identify callable types.

Parameters:

  • x an object or primitive

Returns:

    true if x can be called, otherwise false

Usage:

    if callable (functable) then functable (args) end
case (with, branches)
A rudimentary case statement. Match with against keys in branches table.

Parameters:

  • with expression to match
  • branches table map possible matches to functions

Returns:

    the value associated with a matching key, or the first non-key value if no key matches. Function or functable valued matches are called using with as the sole argument, and the result of that call returned; otherwise the matching value associated with the matching key is returned directly; or else nil if there is no match and no default.

See also:

Usage:

     return case (type (object), {
       table  = "table",
       string = function ()  return "string" end,
                function (s) error ("unhandled type: " .. s) end,
     })
collect ([ifn=std.npairs], ...)
Collect the results of an iterator.

Parameters:

  • ifn func iterator function (default std.npairs)
  • ... ifn arguments

Returns:

    table of results from running ifn on args

See also:

Usage:

     --> {"a", "b", "c"}
     collect {"a", "b", "c", x=1, y=2, z=5}
compose (...)
Compose functions.

Parameters:

  • ... func 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:

     functional.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
cond (expr, branch, ...)
A rudimentary condition-case statement. If expr is "truthy" return branch if given, otherwise expr itself. If the return value is a function or functable, then call it with expr as the sole argument and return the result; otherwise return it explicitly. If expr is "falsey", then recurse with the first two arguments stripped.

Parameters:

  • expr a Lua expression
  • branch a function, functable or value to use if expr is "truthy"
  • ... additional arguments to retry if expr is "falsey"

See also:

Usage:

     -- recursively calculate the nth triangular number
     function triangle (n)
       return cond (
         n <= 0, 0,
         n == 1, 1,
                 function () return n + triangle (n - 1) end)
     end
curry (fn, n)
Curry a function.

Parameters:

  • fn func function to curry
  • n int 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)
filter (pfn[, ifn=std.pairs], ...)
Filter an iterator with a predicate.

Parameters:

  • pfn predicate predicate function
  • ifn func iterator function (default std.pairs)
  • ... iterator arguments

Returns:

    table elements e for which pfn (e) is not "falsey".

See also:

Usage:

     --> {2, 4}
     filter (lambda '|e|e%2==0', std.elems, {1, 2, 3, 4})
flatten (t)
Flatten a nested table into a list.

Parameters:

Returns:

    table a list of all non-table elements of t

Usage:

     --> {1, 2, 3, 4, 5}
     flatten {{1, {{2}, 3}, 4}, 5}
foldl (fn[, d=t[1]], t)
Fold a binary function left associatively. If parameter d is omitted, the first element of t is used, and t treated as if it had been passed without that element.

Parameters:

  • fn func binary function
  • d initial left-most argument (default t[1])
  • t table a table

Returns:

    result

See also:

Usage:

    foldl (functional.operator.quot, {10000, 100, 10}) == (10000 / 100) / 10
foldr (fn[, d=t[1]], t)
Fold a binary function right associatively. If parameter d is omitted, the last element of t is used, and t treated as if it had been passed without that element.

Parameters:

  • fn func binary function
  • d initial right-most argument (default t[1])
  • t table a table

Returns:

    result

See also:

Usage:

    foldr (functional.operator.quot, {10000, 100, 10}) == 10000 / (100 / 10)
id (...)
Identity function.

Parameters:

  • ... arguments

Returns:

    arguments
ireverse (t)
Return a new sequence with element order reversed.

Apart from the order of the elements returned, this function follows the same rules as ipairs for determining first and last elements.

Parameters:

Returns:

    table a new table with integer keyed elements in reverse order with respect to t

See also:

Usage:

     local rielems = functional.compose (functional.ireverse, std.ielems)
     --> bar
     --> foo
     functional.map (print, rielems, {"foo", "bar", [4]="baz", d=5})
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
  2. '|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.

Parameters:

Returns:

    functable compiled lambda string, can be called like a function

Usage:

     -- The following are equivalent:
     lambda '= _1 < _2'
     lambda '|a,b| a<b'
map (fn[, ifn=std.pairs], ...)
Map a function over an iterator.

Parameters:

  • fn func map function
  • ifn func iterator function (default std.pairs)
  • ... iterator arguments

Returns:

    table results

See also:

Usage:

     --> {1, 4, 9, 16}
     map (lambda '=_1*_1', std.ielems, {1, 2, 3, 4})
map_with (fn, tt)
Map a function over a table of argument lists.

Parameters:

  • fn func map function
  • tt table a table of fn argument lists

Returns:

    table new table of fn results

See also:

Usage:

     --> {"123", "45"}, {a="123", b="45"}
     conc = bind (map_with, {lambda '|...|table.concat {...}'})
     conc {{1, 2, 3}, {4, 5}}, conc {a={1, 2, 3, x="y"}, b={4, 5, z=6}}
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.

Parameters:

  • fn func 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.

See also:

Usage:

    if unsupported then vtable["memrmem"] = nop end
product (...)
Functional list product.

Return a list of each combination possible by taking a single element from each of the argument lists.

Parameters:

  • ... operands

Returns:

    result

Usage:

     --> {"000", "001", "010", "011", "100", "101", "110", "111"}
     map (table.concat, ielems, product ({0,1}, {0, 1}, {0, 1}))
reduce (fn, d[, ifn=std.pairs], ...)
Fold a binary function into an iterator.

Parameters:

  • fn func reduce function
  • d initial first argument
  • ifn func iterator function (default std.pairs)
  • ... iterator arguments

Returns:

    result

See also:

Usage:

     --> 2 ^ 3 ^ 4 ==> 4096
     reduce (functional.operator.pow, 2, std.ielems, {3, 4})
shape (dims, t)
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.

Parameters:

  • dims table table of dimensions {d1, ..., dn}
  • t table a table of elements

Returns:

    reshaped list

Usage:

     --> {{"a", "b"}, {"c", "d"}, {"e", "f"}}
     shape ({3, 2}, {"a", "b", "c", "d", "e", "f"})
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.

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 (fn, tt)
Zip a list of tables together with a function.

Parameters:

  • fn function function
  • tt table table of tables

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 list of lists.

See also:

Usage:

     --> {"135", "24"}, {a="1", b="25"}
     conc = bind (zip_with, {lambda '|...|table.concat {...}'})
     conc {{1, 2}, {3, 4}, {5}}, conc {{a=1, b=2}, x={a=3, b=4}, {b=5}}

Types

mnemonic (...)
Signature of a memoize argument normalization callback function.

Parameters:

  • ... arguments

Returns:

    string stable serialized arguments

Usage:

     local mnemonic = function (name, value, props) return name end
     local intern = functional.memoize (mksymbol, mnemonic)
predicate (...)
Signature of a filter predicate callback function.

Parameters:

  • ... arguments

Returns:

    boolean "truthy" if the predicate condition succeeds, "falsey" otherwise

Usage:

     local predicate = lambda '|k,v|type(v)=="string"'
     local strvalues = filter (predicate, std.pairs, {name="Roberto", id=12345})
generated by LDoc 1.4.3 Last updated 2016-01-31 18:35:45