Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IO computation order

Tags:

haskell

I have learned Haskell for some time, but IO monad yet scared me. I have a code

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 

And see "First computation starts" "Second computation starts" and then program will be doing.

I know that there is laisy computation, and really computation starts when writeFile executes. I try to add strictness

    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 

Nothing happens

Well, maybe let expressions are only synonyms and exchanged by compiler? I try to turn functions into 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 

Nevertheless, result is same as above, It's unclear for me.

like image 996
Sergey Sosnin Avatar asked May 12 '26 22:05

Sergey Sosnin


1 Answers

If you want to make sure something has been evaluated, deepseq is your friend. You will have to implement NFData for whatever foo is, but this is usually easy to do. Your main would then become

main = do
  putStrLn "First computation starts"
  firstResult <- return $!! foo
  putStrLn "Second computation starts"
  secondResult <- return $!! bar foo
  writeFile secondResult 
like image 103
Waldheinz Avatar answered May 15 '26 13:05

Waldheinz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!