在 Haskell 中使用 Data.Binary.Get 解析简单的二进制文件
我正在尝试使用 Data.Binary.Get monad 解析 Haskell 中的一个简单的二进制文件。
我的代码的简化版本如下所示:
data MsgString = Definition_msg {
msg_no :: Word16
} deriving (Show)
parseDef :: Get MsgString
parseDef = do
msg_no <- getWord16le
return $ Definition_msg msg_no
parseMain :: Get [MsgString]
parseMain = do
bit <- getWord8
msg <- parseDef
return msg:parseMain
我得到的错误如下:
Prelude> :l example.hs
[1 of 1] Compiling Main ( example.hs, interpreted )
example.hs:23:17:
Couldn't match expected type `[m MsgString]'
against inferred type `Get [MsgString]'
In the second argument of `(:)', namely `parseMain'
In the expression: return msg : parseMain
In the expression:
do { bit <- getWord8;
msg <- parseDef;
return msg : parseMain }
Failed, modules loaded: none.
任何人都可以看到我做错了什么吗?
谢谢!
I am trying to parse a simple binary file in Haskell with the Data.Binary.Get monad.
A simplified version of my code looks like this:
data MsgString = Definition_msg {
msg_no :: Word16
} deriving (Show)
parseDef :: Get MsgString
parseDef = do
msg_no <- getWord16le
return $ Definition_msg msg_no
parseMain :: Get [MsgString]
parseMain = do
bit <- getWord8
msg <- parseDef
return msg:parseMain
And the error I get is the following:
Prelude> :l example.hs
[1 of 1] Compiling Main ( example.hs, interpreted )
example.hs:23:17:
Couldn't match expected type `[m MsgString]'
against inferred type `Get [MsgString]'
In the second argument of `(:)', namely `parseMain'
In the expression: return msg : parseMain
In the expression:
do { bit <- getWord8;
msg <- parseDef;
return msg : parseMain }
Failed, modules loaded: none.
Can anyone see what I do wrong?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是你的最后一行,它解析为:
但这确实不是唯一的问题。当您确实只想要一个
[MsgString]
时,parseMain 的类型为Get [MsgString]
,因此您必须首先运行单子操作:注意,这将获得
的无限列表>MsgString
's 并且不会在没有异常的情况下终止。也许您打算使用 if 语句来保护对parseMain
的递归调用?The issue is your last line, which parses as:
But that really isn't the only problem. parseMain is of type
Get [MsgString]
when you really just want a[MsgString]
so you must run the monadic action first:Notice this will get an infinite list of
MsgString
's and won't terminate without an exception. Perhaps you intended to have an if statement guarding that recursive call toparseMain
?