Haskell IO Progress

I have the following code:

import Control.Monad (unless) import System.IO (isEOF, hFlush, stdout) main :: IO () main = unlessFinished $ do putStr "$ " hFlush stdout getLine >>= putStrLn main where unlessFinished action = isEOF >>= flip unless action 

When I compile and run this code, it displays the cursor at the beginning of an empty line and only after I press [Enter] it will display $ and everything that I wrote.

It would seem that getLine is called before putStr "$ " , even if IO monad guarantees that its actions are called in the order in which they are ordered in the code (or I understand what is written here ). So why is this not working correctly?

+5
source share
1 answer

Actually, the putStr and hFlush are executed before the getLine action, however, before it is executed, isEOF is executed and it does not return until it finds out whether the input is EOF or not, that is, before the line is entered. You can move isEOF right to getLine , for example:

 main :: IO () main = do putStr "$ " hFlush stdout unlessFinished $ do getLine >>= putStrLn main where unlessFinished action = isEOF >>= flip unless action 
+9
source

Source: https://habr.com/ru/post/1237136/


All Articles