Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Lua version, using a more functional style
- -- ~ 23 ms, using LuaJIT 2.0.0-beta5
- -- we use a single function to emulate input ranges
- -- calling the function gets the next item, nil if the range is empty
- function iota(start, upper)
- return function()
- if start >= upper then
- return nil
- end
- local res = start
- start = start + 1
- return res
- end
- end
- function map(range, fn)
- fn = fixfunction(fn, "a")
- return function()
- local val = range()
- if val == nil then
- return nil
- end
- return fn(val)
- end
- end
- function reduce(range, fn)
- fn = fixfunction(fn, "a, b")
- local val = range()
- if val == nil then
- return nil
- end
- while true do
- local val2 = range()
- if val2 == nil then
- break
- end
- val = fn(val, val2)
- end
- return val
- end
- -- std.algorithm style string lambdas support
- function fixfunction(fn, params)
- if type(fn) ~= "function" then
- fn = loadstring("return function(" .. params .. ") return " .. fn .. " end")
- fn = fn()
- end
- return fn
- end
- -- hint: numbers in Lua always use double floating point type
- L = iota(0, 10000000)
- L2 = map(L, function(a) return a / 2 end)
- L3 = map(L2, function(a) return a + 2 end)
- V = reduce(L3, function(a, b) return a + b end)
- -- uncomment this if you love using strings for lambdas
- -- runs as fast as the "proper" version above
- --[[
- L2 = map(L, "a/2")
- L3 = map(L2, "a+2")
- V = reduce(L3, "a+b")
- --]]
- print(V)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement