Created
September 10, 2015 08:48
-
-
Save fritschy/b6b17676d227fdf195b5 to your computer and use it in GitHub Desktop.
Lazy lists in lua, kinda sorta really useless
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env lua5.2 | |
local cryield = coroutine.yield | |
local crwrap = coroutine.wrap | |
function map(f, xs) | |
return crwrap(function() | |
for v in xs do | |
cryield(f(v)) | |
end | |
end) | |
end | |
function takeWhile(p, xs) | |
return crwrap(function() | |
for v in xs do | |
if not p(v) then | |
break | |
end | |
cryield(v) | |
end | |
end) | |
end | |
function take(n, xs) | |
return crwrap(function() | |
local i = 1 | |
for v in xs do | |
if i > n then | |
break | |
end | |
i = i + 1 | |
cryield(v) | |
end | |
end) | |
end | |
function drop(n, xs) | |
return crwrap(function() | |
local i = 1 | |
for v in xs do | |
if i > n then | |
cryield(v) | |
break | |
end | |
i = i + 1 | |
end | |
for v in xs do | |
cryield(v) | |
end | |
end) | |
end | |
function dropWhile(f, xs) | |
return crwrap(function() | |
for v in xs do | |
if not f(v) then | |
cryield(v) | |
break | |
end | |
end | |
for v in xs do | |
cryield(v) | |
end | |
end) | |
end | |
function range(a, b) | |
return crwrap(function() | |
for i = a, b do | |
cryield(i) | |
end | |
end) | |
end | |
function list(...) | |
local l = {...} | |
return crwrap(function() | |
for _, i in ipairs(l) do | |
cryield(i) | |
end | |
end) | |
end | |
function cons(x, xs) | |
return crwrap(function() | |
cryield(x) | |
for v in xs do | |
cryield(v) | |
end | |
end) | |
end | |
function head(xs) | |
return xs() | |
end | |
function tail(xs) | |
xs() | |
return xs | |
end | |
function length(xs) | |
local l = 0 | |
for _ in xs do | |
l = l + 1 | |
end | |
return l | |
end | |
function concat(xs, ys) | |
return crwrap(function() | |
for v in xs do cryield(v) end | |
for v in ys do cryield(v) end | |
end) | |
end | |
-- [start,step,...] | |
function generate(start, step, end_) | |
step = step or 1 | |
return crwrap(function() | |
local n = 1 | |
while end_ == nil or start <= end_ do | |
cryield(start) | |
start = start + step * n | |
n = n + 1 | |
end | |
end) | |
end | |
function repeat_(val) | |
return crwrap(function() | |
while true do | |
cryield(val) | |
end | |
end) | |
end | |
function foldr(f, z, xs) | |
local r = z | |
for v in xs do | |
r = f(r, v) | |
end | |
return r | |
end | |
print(foldr(function(x,z) print(x, z) return x+z end,0,drop(1, | |
dropWhile(function(x) return x<10 end, | |
take(10, | |
takeWhile(function(x) return x<40 end, | |
map(function(x) return x*2 end, | |
tail(cons("moo", | |
generate(0)))))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment