简体   繁体   English

GHC能够尾随调用优化IO操作吗?

[英]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.

相关问题 在C和Haskell的相互递归中编译尾调用优化 - Compiling Tail-Call Optimization In Mutual Recursion Across C and Haskell 是否可以通过O(1)内存使用延迟遍历递归数据结构,尾部调用优化? - Is it possible to lazily traverse a recursive data-structure with O(1) memory usage, tail-call optimized? GHC会优化a * a * a * a * a * a到(a * a * a)*(a * a * a)? - Will GHC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)? 是否建议在尾递归形式中使用递归IO操作? - Is it recommended to use recursive IO actions in the tail recursive form? Haskell:GHC会对此进行优化吗? - Haskell : Will GHC optimize this? GHC IO编译错误 - GHC IO compilation error 如何调用 function glMultiDrawElements:: GLenum -> GHC.Ptr.Ptr GLsizei -> GHC.Ptr.Ptr (GHC.Ptr.Ptr a) -> GLsizei -> IO () - How to call the function glMultiDrawElements :: GLenum -> GHC.Ptr.Ptr GLsizei -> GLenum -> GHC.Ptr.Ptr (GHC.Ptr.Ptr a) -> GLsizei -> IO () 在GHC中,非尾部函数转换为CPS吗? - In GHC are non-tail functions transformed to CPS? Language.Haskell.Interpreter - 如何正确调用IO操作? - Language.Haskell.Interpreter - how to properly call IO actions? 尾位置上下文 GHC 连接点论文是如何形成的? - How are tail-position contexts GHC join points paper formed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM