Last active
August 27, 2020 12:58
-
-
Save noughtmare/4adf5721646969a62dfe056b7e811d57 to your computer and use it in GitHub Desktop.
Convert an `IO String` into an infinite string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Run this example with runhaskell: | |
-- | |
-- $ runhaskell infinite-string-stream.hs | |
-- | |
-- Type in some text and press enter. | |
-- Repeat as long as you like. | |
-- At the end press CTRL-d to quit. | |
-- | |
-- Using unsafeInterleaveIO the text you put in will appear immediately after | |
-- each new line. Without it, the output will only be printed after you quit | |
-- with CTRL-d. | |
import System.IO.Unsafe | |
import System.IO | |
withStringStream :: IO (Maybe String) -> (String -> IO a) -> IO a | |
withStringStream m f = f =<< go | |
where | |
go = do | |
x <- m | |
case x of | |
Just s -> (s ++) <$> unsafeInterleaveIO go | |
Nothing -> return "" | |
input :: IO (Maybe String) | |
input = do | |
b <- isEOF | |
if b | |
then return Nothing | |
else Just <$> getLine | |
main :: IO () | |
main = do | |
hSetEcho stdin False | |
hSetBuffering stdin LineBuffering | |
hSetBuffering stdout NoBuffering | |
withStringStream input print |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment