Haskell CPS 编程风格问题
这是一个使用 CPS 样式将列表中的元素相乘的函数,
mlist xx k = aux xx k
where aux [] nk = nk 1
aux (0:xs) nk = k 0
aux (x:xs) nk = aux xs $ \v -> mul x v nk
如果我将表达式 aux (0:xs) nk = k 0 中的 'k' 更改为 'nk' 会怎样?强>,两者有什么区别?
here is a function multiplies the elements in a list using CPS style
mlist xx k = aux xx k
where aux [] nk = nk 1
aux (0:xs) nk = k 0
aux (x:xs) nk = aux xs $ \v -> mul x v nk
what if I change the 'k' to 'nk' in the expression aux (0:xs) nk = k 0, whats the difference between the two ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
k
始终是传递给mlist
的原始延续,而对于列表 [1, 0]nk
在这种情况下将为\v -> mul 1 v k
(来自aux
的第三种情况)。如果我们假设
mul
定义为mul xyk = k $ x*y
,这不会产生实际差异,因为y
始终是0。但是达到该结果的实际方法是不同的(除非编译器可能进行优化)。k
is always the original continuation passed tomlist
whereas for the list [1, 0]nk
in that case will be\v -> mul 1 v k
(from third case ofaux
).If we assume
mul
is defined asmul x y k = k $ x*y
, this doesn't make a practical difference sincey
will always be 0. But the actual method of arriving at that result is different (barring possible optimizations by the compiler).不同之处在于,原始定义“短路”尾调用应用程序传递的任何构建乘法,而更改后的表达式仅短路测试值 - 它保留了延续函数的构建“版本”。
The difference is that the original definition "short circuits" any built-up multiplications passed by tail call applications, while the changed expression only short-circuits testing the values - it keeps the built-up "version" of the continuation function.