流式 IO
io-streams
是基於流的庫,專注於 Stream 抽象,但是用於 IO。它暴露了兩種型別:
-
InputStream
:只讀智慧手柄 -
OutputStream
:一個只寫的智慧控制代碼
我們可以用 makeInputStream::IO (Maybe a) -> IO (InputStream a)
建立一個流。使用 read::InputStream a -> IO (Maybe a)
從流中讀取 ,其中 Nothing
表示 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