-
-
Save pkulchenko/72b560135d0e4f11f958e756affe49e4 to your computer and use it in GitHub Desktop.
Lazy evaluation on lists (a la Perl6) with Lua... [ FIXED ]
This file contains 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/lua | |
-- Perl6 example -- | |
--[[ | |
my @xs := gather { | |
my $x = 0; | |
my $y = 1; | |
while True { | |
take $x; | |
($x, $y) = ($y, $x + $y); | |
} | |
} | |
for @xs -> $x { | |
say $x; | |
sleep 1; | |
} | |
]]-- | |
-- Lua version -- | |
-- as like Perl 6 ':=" operator -- | |
function bind (lambda) | |
local glue = { | |
-- lazy assignment -- | |
__index = function (table, key) | |
if key > 0 then | |
local value | |
for index = 1, key do | |
if not rawget (table, index) then | |
value = lambda ( ) | |
rawset (table, index, value) | |
end | |
end | |
return table[ key ] | |
end | |
end, | |
-- iterator -- | |
__call = function (table) | |
local index = 0 | |
return function ( ) | |
index = index + 1 | |
return table[ index ] | |
end | |
end | |
} | |
return setmetatable ({ }, glue) | |
end | |
-- short alias Perl6 like -- | |
local gather = coroutine.wrap | |
local take = coroutine.yield | |
-- lazy assignment test -- | |
-- fibonacci sequence -- | |
local xs = bind (gather (function ( ) | |
local x = 0 | |
local y = 1 | |
while true do | |
take (x) | |
x, y = y, x + y | |
end | |
end)) | |
-- iterator test -- | |
-- loop forever -- | |
for x in xs( ) do | |
print (x) | |
os.execute "sleep 1" | |
end | |
-- end of script -- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment