【问题标题】:Is GHC able to tail-call optimize IO actions?GHC 是否能够尾调用优化 IO 操作?
【发布时间】:2009-04-27 03:22:28
【问题描述】:

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

【问题讨论】:

    标签: haskell io tail-recursion


    【解决方案1】:

    因为你的代码相当于

    consume store (x:xs) = putMVar store >> consume store xs
    

    调用实际上并没有发生在尾部位置。但是如果你运行ghc -O并打开优化器,-ddump-simpl选项会显示GHC中间代码的输出,它确实优化成一个尾递归函数,它会编译成一个循环。

    所以答案是默认情况下 GHC 不会对此进行优化;你需要-O 选项。

    (使用 GHC 版本 6.10.1 完成的实验。)

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 2021-05-27
      • 2014-06-09
      • 2020-10-21
      • 2010-10-23
      • 2012-04-18
      • 2011-07-16
      • 2010-11-16
      • 1970-01-01
      相关资源
      最近更新 更多