我学习 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"
然后程序会做什么。
我知道有简单的计算,真正的计算是在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
什么都没发生
好吧,也许 let 表达式只是同义词并由编译器交换?我尝试将功能变成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
尽管如此,结果与上述相同,我不清楚。