| 1 | require "dokidoki.module" |
| 2 | [[ range, ireverse, map, imap, ifoldl, iforeach, irandomize, iconcat, ifilter, copy, build_array, |
| 3 | identity, void, compose ]] |
| 4 | |
| 5 | function range(first, last, step) |
| 6 | step = step or 1 |
| 7 | local result = {} |
| 8 | for i = first, last, step do |
| 9 | result[#result+1] = i |
| 10 | end |
| 11 | return result |
| 12 | end |
| 13 | |
| 14 | function ireverse(a) |
| 15 | local result = {} |
| 16 | local len = #a |
| 17 | for i = 1, len do |
| 18 | result[i] = a[len - i + 1] |
| 19 | end |
| 20 | return result |
| 21 | end |
| 22 | |
| 23 | function map (f, t) |
| 24 | local result = {} |
| 25 | for k, v in pairs(t) do |
| 26 | result[k] = f(v) |
| 27 | end |
| 28 | return result |
| 29 | end |
| 30 | |
| 31 | function imap (f, a) |
| 32 | local result = {} |
| 33 | for i, v in ipairs(a) do |
| 34 | result[i] = f(v) |
| 35 | end |
| 36 | return result |
| 37 | end |
| 38 | |
| 39 | function ifoldl(f, init, a) |
| 40 | for _, v in ipairs(a) do |
| 41 | init = f(init, v) |
| 42 | end |
| 43 | return init |
| 44 | end |
| 45 | |
| 46 | function iforeach (f, a) |
| 47 | for i = 1, #a do |
| 48 | f(a[i]) |
| 49 | end |
| 50 | end |
| 51 | |
| 52 | function irandomize(a) |
| 53 | local result = copy(a) |
| 54 | for i = 1, #result-1 do |
| 55 | local j = math.random(i, #result) |
| 56 | local tmp = result[i] |
| 57 | result[i] = result[j] |
| 58 | result[j] = tmp |
| 59 | end |
| 60 | return result |
| 61 | end |
| 62 | |
| 63 | function iconcat(a1, a2) |
| 64 | local result = copy(a1) |
| 65 | local len = #a1 |
| 66 | for i, v in ipairs(a2) do |
| 67 | result[len + i] = v |
| 68 | end |
| 69 | return result |
| 70 | end |
| 71 | |
| 72 | function ifilter (p, a) |
| 73 | local result = {} |
| 74 | for k, v in ipairs(a) do |
| 75 | if p(v) then result[#result+1] = v end |
| 76 | end |
| 77 | return result |
| 78 | end |
| 79 | |
| 80 | function copy (t) |
| 81 | local result = {} |
| 82 | for k, v in pairs(t) do |
| 83 | result[k] = v |
| 84 | end |
| 85 | return result |
| 86 | end |
| 87 | |
| 88 | function build_array (len, f) |
| 89 | local result = {} |
| 90 | for i = 1, len do |
| 91 | result[i] = f(i) |
| 92 | end |
| 93 | return result |
| 94 | end |
| 95 | |
| 96 | function identity (...) |
| 97 | return ... |
| 98 | end |
| 99 | |
| 100 | function void () |
| 101 | end |
| 102 | |
| 103 | function compose(f, ...) |
| 104 | if select('#', ...) == 0 then |
| 105 | return f |
| 106 | else |
| 107 | local rest = compose(...) |
| 108 | return function (...) |
| 109 | return f(rest(...)) |
| 110 | end |
| 111 | end |
| 112 | end |
| 113 | |
| 114 | return get_module_exports() |