Haskell Language

Streaming IO

Streaming IO

io-streams is Stream-based library that focuses on the Stream abstraction but for IO. It exposes two types:

  • InputStream: a read-only smart handle

  • OutputStream: a write-only smart handle

We can create a stream with makeInputStream :: IO (Maybe a) -> IO (InputStream a). Reading from a stream is performed using read :: InputStream a -> IO (Maybe a), where Nothing denotes an EOF:

import Control.Monad (forever)
import qualified System.IO.Streams as S
import System.Random (randomRIO)

main :: IO ()
main = do
  is <- S.makeInputStream $ randomInt  -- create an InputStream
  forever $ printStream =<< S.read is  -- forever read from that stream
  return ()

randomInt :: IO (Maybe Int)
randomInt = do
  r <- randomRIO (1, 100)
  return $ Just r

printStream :: Maybe Int -> IO ()
printStream Nothing  = print "Nada!"
printStream (Just a) = putStrLn $ show a

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow