Skip to content

Instantly share code, notes, and snippets.

@marcoonroad
Created January 30, 2015 04:22
Show Gist options
  • Select an option

  • Save marcoonroad/a4a3b8af98fb9817a360 to your computer and use it in GitHub Desktop.

Select an option

Save marcoonroad/a4a3b8af98fb9817a360 to your computer and use it in GitHub Desktop.
Simple combinators reactive-like at Lua...
-- supply test --
-- protótipo --
local Supply = {
subs = { } -- funções inscritas --
}
-- construtor --
function Supply: new ( )
return setmetatable ({ subs = { } }, { __index = Supply })
end
-- método para inscrição --
function Supply: tap (F)
return table.insert (self.subs, F)
end
-- método para propagação de "sinais" / "eventos" --
function Supply: more (...)
local A = { ... }
for _, F in ipairs (self.subs) do
F ((unpack or table.unpack) (A))
end
end
-- combinador de transformação -- dualístico -- comum em iteradores e listas --
function Supply: map (F)
local stream = Supply: new ( )
-- propagação modificada --
self: tap (function (...)
return stream: more (F ((unpack or table.unpack) { ... }))
end)
return stream
end
-- combinador filtro -- dualístico -- comum em iteradores e listas --
function Supply: grep (P)
local stream = Supply: new ( )
-- propagação condicional --
self: tap (function (...)
if (P ((unpack or table.unpack) { ... })) then
return stream: more ((unpack or table.unpack) { ... })
end
end)
return stream
end
-- combinador de concatenação -- dualístico -- comum em listas --
function Supply: merge (S)
local stream = Supply: new ( )
-- ambas funções inscritas propagam para a nova stream de eventos --
self: tap (function (...)
return stream: more ((unpack or table.unpack) { ... })
end)
S: tap (function (...)
return stream: more ((unpack or table.unpack) { ... })
end)
return stream
end
-- exemplos --
local listen = Supply: new ( )
listen:
grep (function (X) return X % 2 == 0 end):
tap (function (V) return print ("Even: " .. tostring (V) .. "...") end)
listen:
map (function (X) return (X + 5) ^ 2 end):
tap (print)
listen: more (5)
listen: more (4)
-- adicionando uma nova stream de "eventos" --
local supply = Supply: new ( )
supply: tap (print)
-- mais uma nova stream de eventos --
local merged = supply: merge (listen)
merged: tap (function (V) return print ("From listen or supply: " .. tostring (V) .. "...") end)
supply: more (8)
listen: more (9)
-- endof test --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment