IO计算顺序

时间:2013-09-23 16:21:53

标签: haskell

我已经学习了Haskell一段时间了,但IO monad却吓坏了我。 我有一个代码

main = do
    putStrLn "First computation starts"
    let firstResult = foo -- foo is a pure function
    putStrLn "Second computation starts"
    let secondResult = bar foo -- bar is too pure function
    writeFile secondResult 

然后看"First computation starts" "Second computation starts",然后程序即可。

我知道有laisy计算,真正的计算在writeFile执行时开始。 我尝试添加严格性

    main = do
    putStrLn "First computation starts"
    let !firstResult = foo -- foo is a pure function
    putStrLn "Second computation starts"
    let !secondResult = bar foo -- bar is too pure function
    writeFile secondResult 

什么都没发生

那么,也许让表达式只是同义词并由编译器交换?我尝试将函数转换为IO

main = do
putStrLn "First computation starts"
!firstResult <- return (foo) -- foo is a pure function
putStrLn "Second computation starts"
!secondResult <- return (bar foo) -- bar is too pure function
writeFile secondResult 

尽管如此,结果与上述相同,对我来说还不清楚。

1 个答案:

答案 0 :(得分:5)

如果您想确定某些内容已被评估,deepseq是您的朋友。无论NFData是什么,您都必须实施foo,但这通常很容易实现。您的main将成为

main = do
  putStrLn "First computation starts"
  firstResult <- return $!! foo
  putStrLn "Second computation starts"
  secondResult <- return $!! bar foo
  writeFile secondResult