-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.lua
80 lines (63 loc) · 2.55 KB
/
sample.lua
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
local t = require 'transducers'
local f = require 'functional'
local tr = require 'transformers'
local inspect = require 'inspect'
local function plus1(n)
return n + 1
end
local function odd(n)
return n % 2 == 0
end
local function push(tbl, result)
table.insert(tbl, result)
return tbl
end
local arr = {1,2,3,4}
local transducer = t.map(plus1)
local result = t.transduce(transducer, push, arr)
print('demonstrating transduce.', inspect(result))
-- { 2, 3, 4, 5 }
local transducer = f.compose(t.map(plus1), t.map(plus1), t.map(plus1), t.map(plus1))
local result = t.transduce(transducer, push, arr)
print('demonstrating compose.', inspect(result))
-- { 5, 6, 7, 8 }
local transducer = f.compose(t.filter(odd), t.map(plus1), t.map(plus1), t.map(plus1))
local result = t.transduce(transducer, push, arr)
print('demonstrating filter.', inspect(result))
-- { 4, 6 }
local transducer = f.compose(t.remove(odd), t.map(plus1), t.map(plus1), t.map(plus1))
local result = t.transduce(transducer, push, arr)
print('demonstrating response.', inspect(result))
-- { 5, 7 }
local transducer = f.compose(t.remove(odd), t.map(plus1), t.map(plus1), t.map(plus1))
local result = t.transduce(transducer, tr.sum, arr)
print('demonstrating transformation and then reduction with sum.', inspect(result))
-- 12
local transducer = f.compose(t.remove(odd), t.map(plus1), t.map(plus1), t.map(plus1))
local result = t.transduce(transducer, tr.mult, arr)
print('demonstrating transformation and then reduction with mult.', inspect(result))
-- 35
local transducer = t.map(plus1)
local result = t.transduce(transducer, tr.append, arr)
print('demonstrating that push is equivalent to the append transformer.', inspect(result))
-- { 2, 3, 4, 5 }
local transducer = f.compose(t.drop(2), t.map(plus1))
local result = t.transduce(transducer, tr.append, arr)
print('demonstrating drop.', inspect(result))
-- { 4, 5 }
local transducer = f.compose(t.take(2), t.map(plus1))
local result = t.transduce(transducer, tr.append, arr)
print('demonstrating take.', inspect(result))
-- { 2, 3 }
local transducer = f.compose(t.drop(1), t.take(2), t.drop(1))
local result = t.transduce(transducer, tr.append, arr)
print('demonstrating composition of take and drop.', inspect(result))
-- { 3 }
local transducer = f.compose(t.map(plus1), t.filter(odd))
local result = t.into(transducer, {}, arr)
print('demonstrating into.', inspect(result))
-- { 3, 5 }
local transducer = f.compose(t.drop(1), t.take(4), t.drop(1))
local result = t.into(transducer, '', 'transducers')
print('demonstrating generality of iteration.', inspect(result))
-- "ans"