Rumca
Rumca

Reputation: 1829

In Haskell, how to flush Data.Text every line?

How can I change this program to immediately process every line of text in case of interactive input? Preferably flush buffer every newline character.

main = do
  input <- T.getContents
  mapM_ T.putStrLn $ T.lines input

Update: Something is still missing. Take a look (???? is after newline, stdout is printed out after reaching EOF on stdin) :

> cat Test.hs
import System.IO
import Data.Text as T
import Data.Text.IO as T

main = do
    hSetBuffering stdout LineBuffering
    input <- T.getContents
    mapM_ T.putStrLn $ T.lines input
> runhaskell Test.hs
a
????
a
????
> runhaskell --version
runghc 7.6.3
>

Upvotes: 1

Views: 722

Answers (2)

&#216;rjan Johansen
&#216;rjan Johansen

Reputation: 18199

It seems like you want to use lazy input to interleave reading lines and handling them.

getContents from Data.Text.IO is not lazy, and will read everything before returning anything at all.

Import the version from Data.Text.Lazy.IO instead.

Upvotes: 0

bheklilr
bheklilr

Reputation: 54078

You want to use hSetBuffering from System.IO:

import System.IO

main = do
    hSetBuffering stdout LineBuffering
    input <- T.getContents
    mapM_ T.putStrLn $ T.lines input

Upvotes: 8

Related Questions