Functional programming on complex data structures in Zenroom

The LAMBDA module is an extension which provides support for functional programming. It provides common operations on tables, arrays, lists, collections, objects, and a lot more.

The LAMBDA module is a slight adaptation of Moses, which is also deeply inspired by Underscore.js.

Table of Contents

Adding the functional module to your script

A large set of functions that can be classified into four categories:

  • Table functions, which are mostly meant for tables, i.e Lua tables which contains both an array-part and a hash-part,
  • Array functions, meant for array lists (or sequences),
  • Utility functions,
  • Object functions.

[⬆]

Table functions

clear (t)

Clears a table. All its values becomes nil. It returns the passed-in table.

each (t, f, …)

Aliases: LAMBDA.forEach.

Iterates over each key-value pair in table.

The table can be map-like (array part and hash-part).

Can index and assign in an outer table or in the passed-in table:

eachi (t, f, …)

Aliases: LAMBDA.forEachi.

Iterates only on integer keys in a sparse array table.

The given array can be sparse, or even have a hash-like part.

at (t, …)

Collects all values at some specific keys and returns them in an array.

count (t, value)

Counts the number of occurences of a given value in a table.

Returns the size of the list in case no value was provided.

countf (t, f, …)

Count the number of occurences of all values passing an iterator test.

cycle (t, n)

Aliases: LAMBDA.loop.

Returns a function which iterates on each key-value pair in a given table (similarly to LAMBDA.each), except that it restarts iterating again n times. If n is not provided, it defaults to 1.

Supports array-like tables and map-like tables.

map (t, f, …)

Aliases: LAMBDA.collect.

Executes a function on each key-value pairs.

It also maps key-value pairs to key-value pairs

reduce (t, f, state)

Aliases: LAMBDA.inject, LAMBDA.foldl.

Can sums all values in a table.

Or concatenates all values.

reduceby (t, f, state, pred, …)

Reduces a table considering only values matching a predicate. For example,let us define a set of values.

We can also define some predicate functions.

Then we can perform reduction considering only negative values :

Or only positive values :

reduceRight (t, f, state)

Aliases: LAMBDA.injectr, LAMBDA.foldr.

Similar to LAMBDA.reduce, but performs from right to left.

mapReduce (t, f, state)

Aliases: LAMBDA.mapr.

Reduces while saving intermediate states.

mapReduceRight (t, f, state)

Aliases: LAMBDA.maprr.

Reduces from right to left, while saving intermediate states.

include (t, value)

Aliases: LAMBDA.any, LAMBDA.some, LAMBDA.contains.

Looks for a value in a table.

Handles iterator functions.

detect (t, value)

Returns the index of a value in a table.

Handles iterator functions.

where (t, props)

Looks through a table and returns all the values that matches all of the key-value pairs listed in props.

findWhere (t, props)

Looks through a table and returns the first value that matches all of the key-value pairs listed in props.

select (t, f, …)

Aliases: LAMBDA.filter.

Collects values passing a validation test.

reject (t, f, …)

Aliases: LAMBDA.reject.

Removes all values failing a validation test:

all (t, f, …)

Aliases: LAMBDA.every.

Checks whether or not all elements pass a validation test.

invoke (t, method, …)

Invokes a given function on each value in a table

Can reference the method of the same name in each value.

pluck (t, property)

Fetches all values indexed with specific key in a table of objects.

max (t, transform, …)

Returns the maximum value in a collection.

Can take an iterator function to extract a specific property.

min (t, transform, …)

Returns the minimum value in a collection.

Can take an iterator function to extract a specific property.

shuffle (t, seed)

Shuffles a collection.

same (a, b)

Tests whether or not all values in each of the passed-in tables exists in both tables.

sort (t, comp)

Sorts a collection.

Handles custom comparison functions.

sortBy (t, transform, comp)

Sorts items in a collection based on the result of running a transform function through every item in the collection.

The transform function can also be a string name property.

As seen above, the defaut comparison function is the ‘<’ operator. For example, let us supply a different one to sort the list of people by decreasing age order :

The transform function defaults to LAMBDA.indentity and in that case, LAMBDA.sortBy behaves like LAMBDA.sort.

groupBy (t, iter, …)

Groups values in a collection depending on their return value when passed to a predicate test.

countBy (t, iter, …)

Splits a table in subsets and provide the count for each subset.

size (…)

When given a table, provides the count for the very number of values in that table.

When given a vararg list of argument, returns the count of these arguments.

containsKeys (t, other)

Checks whether a table has all the keys existing in another table.

sameKeys (tA, tB)

Checks whether both tables features the same keys:

[⬆]

Array functions

sample (array, n, seed)

Samples n values from array.

n defaults to 1. In that case, a single value will be returned.

An optional 3rd argument seed can be passed for deterministic random sampling.

sampleProb (array, prob, seed)

Returns an array of values randomly selected from a given array. In case seed is provided, it is used for deterministic sampling.

toArray (…)

Converts a vararg list of arguments to an array.

find (array, value, from)

Looks for a value in a given array and returns the position of the first occurence.

It can also start the search at a specific position in the array:

reverse (array)

Reverses an array.

fill (array, value, i, j)

Replaces all elements in a given array with a given value.

It can start replacing value at a specific index.

It can replace only values within a specific range.

In case the upper bound index i greather than the array size, it will enlarge the array.

selectWhile (array, f, …

Aliases: LAMBDA.takeWhile.

Collects values as long as they pass a given test. Stops on the first non-passing test.

dropWhile (array, f, …

Aliases: LAMBDA.rejectWhile.

Removes values as long as they pass a given test. Stops on the first non-passing test.

sortedIndex (array, value, comp, sort)

Returns the index at which a value should be inserted to preserve order.

Can take a custom comparison functions.

indexOf (array, value)

Returns the index of a value in an array.

lastIndexOf (array, value)

Returns the index of the last occurence of a given value in an array.

findIndex (array, predicate, …)

Returns the first index at which a predicate passes a truth test.

findLastIndex (array, predicate, …)

Returns the last index at which a predicate passes a truth test.

addTop (array, …)

Adds given values at the top of an array. The latter values bubbles at the top.

push (array, …)

Adds given values at the end of an array.

pop (array, n)

Aliases: LAMBDA.shift.

Removes and returns the first value in an array.

unshift (array, n)

Removes and returns the last value in an array.

pull (array, …)

Aliases: LAMBDA.remove.

Removes all provided values from a given array.

removeRange (array, start, finish)

Aliases: LAMBDA.rmRange, LAMBDA.chop.

Trims out all values index within a range.

chunk (array, f, …)

Iterates over an array aggregating consecutive values in subsets tables, on the basis of the return value of f(key,value,...). Consecutive elements which return the same value are aggregated together.

slice (array, start, finish)

Aliases: LAMBDA.sub.

Slices and returns a part of an array.

first (array, n)

Aliases: LAMBDA.head, LAMBDA.take.

Returns the first N elements in an array.

initial (array, n)

Excludes the last N elements in an array.

last (array, n)

Aliases: LAMBDA.skip.

Returns the last N elements in an array.

rest (array, index)

Aliases: LAMBDA.tail.

Trims out all values indexed before index.

nth (array, index)

Returns the value at index.

compact (array)

Trims out all falsy values.

flatten (array, shallow)

Flattens a nested array.

When given arg “shallow”, flatten only at the first level.

difference (array, array2)

Aliases: LAMBDA.without, LAMBDA.diff.

Returns values in the given array not present in a second array.

union (…)

Produces a duplicate-free union of all passed-in arrays.

intersection (array, …)

Returns the intersection (common-part) of all passed-in arrays:

symmetricDifference (array, array2)

Aliases: LAMBDA.symdiff,LAMBDA.xor.

Returns values in the first array not present in the second and also values in the second array not present in the first one.

unique (array)

Aliases: LAMBDA.uniq.

Makes an array duplicate-free.

isunique (array)

Aliases: LAMBDA.isuniq.

Checks if a given array contains no duplicate value.

zip (…)

Aliases: LAMBDA.transpose.

Zips values from different arrays, on the basis on their common keys.

append (array, other)

Appends two arrays.

interleave (…)

Interleaves values from passed-in arrays.

interpose (value, array)

Interposes a value between consecutive values in an arrays.

range (…)

Generates an arithmetic sequence.

In case a single value is provided, it generates a sequence from 0 to that value.

LAMBDA.range(3) -- => "{0,1,2,3}"

The incremental step can also be provided as third argument.

rep (value, n)

Generates a list of n repetitions of a value.

partition (array, n, pad)

Aliases: LAMBDA.part.

Returns an iterator function for partitions of a given array.

In case the last partition has less elements than desired, a 3rd argument can be supplied to adjust the partition size.

sliding (array, n, pad)

Returns an iterator function which provides overlapping subsequences of a given array.

In case the last subsequence wil not match the exact desired length, it can be adjusted with a 3rd argument pad.

permutation (array)

Aliases: LAMBDA.perm.

Returns an iterator function for permutations of a given array.

invert (array)

Aliases: LAMBDA.mirror.

Switches key-value pairs:

concat (array, sep, i, j)

Aliases: LAMBDA.join.

Concatenates a given array values:

[⬆]

Utility functions

noop ()

The no-operation function. Takes nothing, returns nothing. It is being used internally.

identity (value)

Returns the passed-in value.
This function is internally used as a default transformation function.

constant (value)

Creates a constant function. This function will continuously yield the same output.

memoize (f, hash)

Aliases: LAMBDA.cache.

Memoizes a slow-running function. It caches the result for a specific input, so that the next time the function is called with the same input, it will lookup the result in its cache, instead of running again the function body.

once (f)

Produces a function that runs only once. Successive calls to this function will still yield the same input.

before (f, count)

Returns a version of f that will run no more than count times. Next calls will keep yielding the results of the (n-th)-1 call.

after (f, count)

Produces a function that will respond only after a given number of calls.

compose (…)

Composes functions. Each function consumes the return value of the one that follows.

pipe (value, …)

Pipes a value through a series of functions.

complement (f)

Returns a function which returns the logical complement of a given function.

juxtapose (value, …)

Aliases: LAMBDA.juxt.

Calls a sequence of functions with the same input.

wrap (f, wrapper)

Wraps a function inside a wrapper. Allows the wrapper to execute code before and after function run.

times (n, iter, …)

Calls a given function n times.

bind (f, v)

Binds a value to be the first argument to a function.

bind2 (f, v)

Binds a value to be the second argument to a function.

bindn (f, …)

Binds a variable number of values to be the first arguments to a function.

bindAll (obj, …)

Binds methods to object. As such, when calling any of these methods, they will receive object as a first argument.

uniqueId (template, …)

Aliases: LAMBDA.uid.

Returns an unique integer ID.

Can handle string templates for formatted output.

Or a function, for the same purpose.

iterator(f, x)

Aliases: LAMBDA.iter.

Returns an iterator function which constinuously applies a function f onto an input x. For example, let us go through the powers of two.

array (…)

Iterates a given iterator function and returns its values packed in an array.

flip (f)

Creates a function of f with arguments flipped in reverse order.

over (…)

Creates a function that invokes a set of transforms with the arguments it receives.
One can use use for example to get the tuple of min and max values from a set of values

overEvery (…)

Creates a validation function. The returned function checks if all of the given predicates return truthy when invoked with the arguments it receives.

overSome (…)

Creates a validation function. The returned function checks if any of the given predicates return truthy when invoked with the arguments it receives.

overArgs (f, …)

Creates a function that invokes f with its arguments transformed

In case the number of arguments is greater than the number of transforms, the remaining args will be left as-is.

partial (f, …)

Partially apply a function by filling in any number of its arguments.

The string '_' can be used as a placeholder in the list of arguments to specify an argument that should not be pre-filled, but is rather left open to be supplied at call-time.

partialRight (f, …)

Like LAMBDA.partial, it partially applies a function by filling in any number of its arguments, but from the right.

The string '_', as always, can be used as a placeholder in the list of arguments to specify an argument that should not be pre-filled, but is rather left open to be supplied at call-time. In that case, the first args supplied at runtime will be used to fill the initial list of args while the remaining will be prepended.

curry (f, n_args)

Curries a function. If the given function f takes multiple arguments, it returns another version of f that takes a single argument (the first of the arguments to the original function) and returns a new function that takes the remainder of the arguments and returns the result.

n_args defaults to 2.

time (f, …)

Returns the execution time of f (...) in seconds and its results.

[⬆]

Object functions

keys (obj)

Collects the names of an object attributes.

values (obj)

Collects the values of an object attributes.

kvpairs (obj)

Converts an object to an array-list of key-value pairs.

toObj

Converts an array list of kvpairs to an object where keys are taken from the 1rst column in the kvpairs sequence, associated with values in the 2nd column.

property (key)

Returns a function that will return the key property of any passed-in object.

propertyOf (obj)

Returns a function that will return the key property of any passed-in object.

toBoolean (value)

Converts a given value to a boolean.

extend (destObj, …)

Extends a destination object with the properties of some source objects.

functions (obj, recurseMt)

Aliases: LAMBDA.methods.

Returns all functions names within an object.

clone (obj, shallow)

Clones a given object.

tap (obj, f, …)

Invokes a given interceptor function on some object, and then returns the object itself. Useful to tap into method chaining to hook intermediate results. The pased-interceptor is prototyped as f(obj,...).

has (obj, key)

Checks if an object has a given attribute.

pick (obj, …)

Aliases: LAMBDA.choose.

Collects whilelisted properties of a given object.

omit (obj, …)

Aliases: LAMBDA.drop.

Omits blacklisted properties of a given object.

template (obj, template)

Aliases: LAMBDA.defaults.

Applies a template on an object, preserving existing properties.

isEqual (objA, objB, useMt)

Aliases: LAMBDA.compare.

Compares objects:

result (obj, method, …)

Calls an object method, passing it as a first argument the object itself.

isTable (t)

Is the given argument an object (i.e a table) ?

isCallable (obj)

Is the given argument callable ?

isArray (obj)

Is the given argument an array (i.e. a sequence) ?

isIterable (obj)

Checks if the given object is iterable with pairs.

isEmpty (obj)

Is the given argument empty ?

isString (obj)

Is the given argument a string ?

isFunction (obj)

Is the given argument a function ?

isNil (obj)

Is the given argument nil ?

isNumber (obj)

Is the given argument a number ?

isNaN (obj)

Is the given argument NaN ?

isFinite (obj)

Is the given argument a finite number ?

isBoolean (obj)

Is the given argument a boolean ?

isInteger (obj)

Is the given argument an integer ?

[⬆]

Chaining

Method chaining (also known as name parameter idiom), is a technique for invoking consecutively method calls in object-oriented style. Each method returns an object, and methods calls are chained together. The @functional module offers chaining for your perusal.
Let’s use chaining to get the count of evey single word in some lyrics (case won’t matter here).

For convenience, you can also use _(value) to start chaining methods, instead of LAMBDA.chain(value).

Note that one can use :value() to unwrap a chained object.

[⬆]

Import

All library functions can be imported in a context using import into a specified context.

When no context was provided, it defaults to the global environment _G.

Passing noConflict argument leaves untouched conflicting keys while importing into the context.

[⬆]

generated by LDoc 1.4.3 Last updated 2018-10-01 18:53:47
]==]