【发布时间】:2014-07-01 19:45:19
【问题描述】:
我一直想知道是否可以在 Lua 中实现延迟执行,.NET Linq 风格,只是为了好玩。
在 .NET 中,我们可以创建称为IEnumerable 的元素序列。然后可以通过各种方式过滤这些元素,例如 map/reduce (Select(predicate), Where(predicate)),但这些过滤器的计算仅在您枚举 IEnumerable 时执行 - 它被延迟。
我一直在尝试在 Lua 中实现类似的功能,虽然我对 Lua 很生疏并且有一段时间没有接触过它。我想避免使用已经为我执行此操作的库,因为我希望能够在可能的情况下在纯 Lua 中执行此操作。
我的想法是,也许可以使用协程..
Enumerable = {
-- Create an iterator and utilize it to iterate
-- over the Enumerable. This should be called from
-- a "for" loop.
each = function(self)
local itr = Enumerable.iterator(self)
while coroutine.status(itr) ~= 'dead' do
return function()
success, yield = coroutine.resume(itr)
if success then
return yield
else
error(1, "error while enumerating")
end
end
end
end,
-- Return an iterator that can be used to iterate
-- over the elements in this collection.
iterator = function(self)
return coroutine.create(function()
for i = 1, #self do
coroutine.yield(self[i])
end
end)
end
}
tbl = {1, 2, 3}
for element in Enumerable.each(tbl) do
print(element)
end
table.insert(tbl, 4)
for element in Enumerable.each(tbl) do
print(element)
end
然而,在写完这篇文章后,我意识到这并不是真正的延迟执行。这只是使用绿色线程的美化迭代器。
我正在尝试使用我已经知道的语言来实现它,以便更好地了解函数式编程的工作原理。
想法?
【问题讨论】:
-
哎呀,错误参数是错误的方法。忽略这一点,:)
-
您的问题是什么? Lua 不是函数式语言。
-
"想知道是否可以实现延迟执行,..在Lua中..."
-
另外,@Lua 不是函数式语言,section 6 of PIL 不同意你的观点。它不是像 Haskell 那样的纯函数式语言,但它具有函数式元素(即是一流的成员),我想知道是否有可能在 Lua 中实现延迟执行的概念,就像我在问题中所说的那样。当我的问题背后的前提在第一行时,我真的不明白“不清楚我在问什么”。
标签: lua lazy-evaluation deferred-execution