public
Description: A library of higher-order functions for Lua
Homepage: http://www.samsarin.com/blog/lua-functional
Clone URL: git://github.com/samsarin/lua-functional.git
lua-functional / README
100644 53 lines (39 sloc) 2.37 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
`lua-functional` provides a set of higher-order functions typically found in
functional languages.
 
* Homepage: [http://www.samsarin.com/blog/lua-functional](http://www.samsarin.com/blog/lua-functional)
* Download: [http://github.com/samsarin/lua-functional](http://github.com/samsarin/lua-functional)
* Current Version: 0.1
* License: [MIT License](http://www.opensource.org/licenses/mit-license.php)
 
### Concepts {#concepts}
 
#### Sequences {#sequence}
 
This library provides several functions that work with a `sequence`. A sequence
as defined by this library is something that can be iterated over. A Lua table
is a sequence and can be passed to any function that accepts a sequence. In
addition, it is possible to use a "wrapped iterator" as a sequence. A
wrapped iterator allows a custom iterator to be used instead of a table.
 
As a contrived example, you may want to concatenate a sparse array of strings
into a single string. In Lua, the end of the array is inidcated by a nil value,
so the traditional array iterator, [ipairs][], would stop concatenation as soon
as an element in the array is nil. However, you can use a custom iterator
to achieve the desired effect:
 
    local array = { 'a', 'b', 'c', nil, 'e' }
    local sequence = functional.wrap_iter(functional.nipairs(array))
    local concatenate = function(t, v) return v and t .. v or t end
    local result = functional.reduce(concatenate, "", sequence)
    print(result)
 
results in:
 
    abce
 
The example above uses a custom iterator from the functional module, [nipairs](#nipairs),
which iterates through a spare array until it hits the last index. The iterator
is "wrapped" with [wrap_iter](#wrap_iter), which creates a single object that
can be passed as a sequence to a higher-order function.
 
#### Tables vs. Arrays
 
In Lua the most basic data structure is a table, not a list as in most
functional languages. Most higher-order functions in this project treat
sequences as arrays. That is, they are treated as if they have a well-defined
order (determined by numeric index), the values of non-numeric keys are ignored,
and the keys are not passed to functions.
 
Only where specifically stated do higher-order functions use tables as an
unordered collection of key/value pairs.
 
[ipairs]: http://www.lua.org/manual/5.1/manual.html#pdf-ipairs
[generic for]: http://www.lua.org/pil/7.2.html