开发者

Haskell: Monads and the (:) operator

开发者 https://www.devze.com 2023-02-19 18:40 出处:网络
I have the following: parseExtensions :: GHC.Int.Int64 -> Get [Word32] parseExtensions size = do br <- bytesRead

I have the following:

parseExtensions :: GHC.Int.Int64 -> Get [Word32]
parseExtensions size = do
    br <- bytesRead
    if (size - br > 20) 
        then do
            ext  <- parseExtension
            exts <- parseExtensions size
            return $ ext : exts
        else return []

parseExtension :: Get Word32
parseExtension = do
    name <- getWor开发者_运维技巧d32be
    size <- getWord32be
    info <- getBytes (fromIntegral size)
    return name

The idea is pretty simple. I'm using Data.Binary.Get to read data off a file. As long as I still have data available (size - br > 20), parse it and repeat.

Is there a simpler/shorter/better way to write the "then" in the parseExtensions function? Can't help but feel I can get some sort of tail recursion or something going.


Shorter:

liftM2 (:) parseExtension (parseExtensions size)

Better, I'm not sure :-\

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号