流式 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