Exception 如何使用unsafeInterleaveIO处理异常?
假设我要打开一个文件并解析它的内容,我想懒洋洋地这样做:Exception 如何使用unsafeInterleaveIO处理异常?,exception,haskell,lazy-evaluation,Exception,Haskell,Lazy Evaluation,假设我要打开一个文件并解析它的内容,我想懒洋洋地这样做: parseFile :: FilePath -> IO [SomeData] parseFile path = openBinaryFile path ReadMode >>= parse' where parse' handle = hIsEOF handle >>= \eof -> do if eof then hClose handle >> return []
parseFile :: FilePath -> IO [SomeData]
parseFile path = openBinaryFile path ReadMode >>= parse' where
parse' handle = hIsEOF handle >>= \eof -> do
if eof then hClose handle >> return []
else do
first <- parseFirst handle
rest <- unsafeInterleaveIO $ parse' handle
return (first : rest)
parseFile::FilePath->IO[SomeData]
parseFile path=openBinaryFile path ReadMode>>=parse'其中
解析'handle=hIsEOF handle>>=\eof->do
如果是eof,则hClose句柄>>返回[]
否则会
首先不使用openBinaryFile
,您可以使用with binaryfile
:
parseFile :: FilePath -> ([SomeData] -> IO a) -> IO a
parseFile path f = withBinaryFile path ReadMode $ \h -> do
values <- parse' h
f values
where
parse' = ... -- same as now
parseFile::FilePath->([SomeData]->IO a)->IO a
parseFile path f=withBinaryFile path ReadMode$\h->do
价值观
parseFile :: MonadResource m => FilePath -> Producer m SomeData
parseFile path = bracketP
(openBinaryFile path ReadMode)
hClose
loop
where
loop handle = do
eof <- hIsEOF handle
if eof
then return ()
else parseFirst handle >>= yield >> loop handle