[英]Is GHC able to tail-call optimize IO actions?
Will GHC perform tail-call optimization on the following function by default? GHC默认会对以下函数执行尾调用优化吗? 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.
关于它的唯一奇怪的事情是它递归地定义了一个IO动作,但我不明白为什么这不是TCO。
import Control.Concurrent.MVar
consume :: MVar a -> [a] -> IO ()
consume _ [] = return ()
consume store (x:xs) = do putMVar store x
consume store xs
Since your code is equivalent to 因为你的代码相当于
consume store (x:xs) = putMVar store >> consume store xs
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. 但是如果你运行
ghc -O
并打开优化器, -ddump-simpl
选项将显示GHC中间代码的输出,它确实优化为尾递归函数,它将编译成循环。
So the answer is GHC won't optimize this by default; 所以答案是GHC默认不会对此进行优化; you need the
-O
option. 你需要
-O
选项。
(Experiments done with GHC version 6.10.1.) (使用GHC版本6.10.1完成的实验。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.