LuaStream is a Lua library which provides streaming APIs. So, users can deal with finite/infinite sequences in a functional way, like that in Clojure and other functional programming languages.
Table of Contents
A stream is a table,
- Whose metatable is
Stream
. - There is an field named by
_stream
, which is a coroutine generating items.
Take from_list
as an example:
function cons.from_list(lst)
local res = {
_stream = function()
for i = 1, #lst do
coroutine.yield(lst[i])
end
end
}
return setmetatable(res, Stream)
end
from_list
generates items in a list one by one.
repeated
generates a same item repeatedly.
range
generates numbers from a start value to a stop value with specified increment.
range(start, stop)
: generates numbers fromstart
(inclusive) tostop
(exclusive) with default increment 1.range(start, stop, inc)
: generates numbers fromstart
(inclusive) tostop
(exclusive) with specified incrementincr
.stop
can be smaller thanstart
whenincr
is negative.
iterate(init, f)
generates an infinite stream
init, f(init), f(f(init)), ...
zip
accepts 0 or more streams,
and each time generates a list of values from every streams.
collect
collects all items of a stream into a list.
collect()
returns a new list.collects(lst)
appends all items intolst
and returns that.
last()
returns the last item of a stream.
first()
returns the first item of a stream.
map
accepts a function, and applies it to each item.
For example, the following snippet generates 2, 3 and 4.
from_list({1, 2, 3})
:map(function(x)
return x + 1
end)
accumulate
accepts a function and its initial state.
Each time the function is applied on its current state and the current value from the stream,
and the result will be the next state.
For example, the following snippet generates 1 (0+1), 3 (1+2) and 6 (3+3).
from_list({1, 2, 3})
:accumulate(
0,
function(state, value)
return state + value
end)
chain
chains a stream to another.
take(n)
truncates a stream from the n-th item.
drop(n)
truncates the first n items from a stream.
flatten
flattens all streams inside a stream.