我可能不太了解 IO 单子(monad)。
如果我编写了一个预计将运行数月的应用程序,同时记录其进度,IO monad 是否会将所有日志信息保存在 RAM 中直到最后?
来自 IO Inside 上的博客, Haskell 将世界建模为
main :: RealWorld -> ((), RealWorld)
这样 IO 不会在代码的 Haskell 部分执行期间发生,而只会在应用程序从
main
返回时发生.我可能完全误解了这一点。谁能解释一下当 Haskell 真的做 IO 吗?
最佳答案
will the IO monad hold all of the log information in RAM until the end?
不,您不应该将“IO monad”视为执行操作的东西。这只是表示命令式程序的一种数学方式。原始的命令式程序类似于
getChar
; >>=
用于将两个程序粘合到一个更大的命令式程序中。 IO monad 是所有命令式程序的集合。考虑一个程序,例如
main = putStr "Hello, " >> putStrLn "world!"
这意味着:
main
是执行程序putStr "Hello, "
的程序,完成后,执行程序putStrLn "world!"
. Haskell 解释器或编译后的程序不需要在内存中保留任何状态,除了指令指针,即“我们在哪里,接下来我们要执行什么”。RealWorld -> ((), RealWorld)
隐喻可能会让你感到困惑,因为它似乎意味着将外部世界的状态转换为必须完整计算的新状态,之后可以更新世界以反射(reflect)计算的状态。这根本不是发生的事情。 Haskell wiki 对此提出警告:The following story about IO is incorrect in that it cannot actually explain some important aspects of IO (including interaction and concurrency).
关于Haskell IO Monad 和内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10880713/