GHC 能够尾部调用优化 IO 操作吗?
GHC 会默认对以下函数执行尾调用优化吗? 唯一奇怪的是它递归地定义 IO 操作,但我不明白为什么这不能实现 TCO。
import Control.Concurrent.MVar
consume :: MVar a -> [a] -> IO ()
consume _ [] = return ()
consume store (x:xs) = do putMVar store x
consume store xs
Will GHC perform tail-call optimization on the following function by default? The only weird thing about it is that it is recursively defining an IO action, but I don't see why this couldn't be TCO'd.
import Control.Concurrent.MVar
consume :: MVar a -> [a] -> IO ()
consume _ [] = return ()
consume store (x:xs) = do putMVar store x
consume store xs
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于你的代码相当于
调用实际上并没有发生在尾部位置。 但是,如果您运行 ghc -O 并打开优化器,则 -ddump-simpl 选项将向您显示 GHC 中间代码的输出,并且它确实会优化为尾递归函数,它将编译成循环。
所以答案是 GHC 默认不会对此进行优化; 您需要
-O
选项。(使用 GHC 版本 6.10.1 进行的实验。)
Since your code is equivalent to
the call does not actually occur in tail position. But if you run
ghc -O
and turn on the optimizer, the-ddump-simpl
option will show you the output of GHC's intermediate code, and it does indeed optimize into a tail-recursive function, which will compile into a loop.So the answer is GHC won't optimize this by default; you need the
-O
option.(Experiments done with GHC version 6.10.1.)