Skip to content

Instantly share code, notes, and snippets.

@noughtmare
Last active August 27, 2020 12:58
Show Gist options
  • Save noughtmare/4adf5721646969a62dfe056b7e811d57 to your computer and use it in GitHub Desktop.
Save noughtmare/4adf5721646969a62dfe056b7e811d57 to your computer and use it in GitHub Desktop.
Convert an `IO String` into an infinite string.
-- 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