我可以用药剂或Erlang这样做:
s = "my binary string"
<<head::binary-size(6), _rest::binary>> = s
head ===> "my bin"
s2 = <<18, 22, 13, 44, 52, 99>>
<<head2::binary-size(4), _rest::binary>> = s2
head2 ===> <<18, 22, 13, 44>>也就是说,head和head2是我感兴趣的结果的变量。
我熟悉哈斯克尔的binary库。我还没有在它中找到类似的功能- https://hackage.haskell.org/package/binary-0.10.0.0/docs/Data-Binary-Get.html#t:Get
在Haskell中,特别是在binary库中,有方法可以这样做吗?
发布于 2020-04-23 07:09:43
Haskell binary中的等效特性是the getByteString function。
getByteString :: Int -> Get ByteString
getByteString 6 :: Get ByteString
example = runGet (getByteString 6) "my binary string" :: ByteString使用do-表示法组成Get解析器.还有getRemainingLazyByteString来获取字节字符串的其余部分,但是要注意,尽管它对于Elixir/Erlang风格的解析很有用,但在Haskell中,解析器的组合包含了其中的大部分内容:
getThreeBS :: Get (ByteString, ByteString, ByteString)
getThreeBS = do
x <- getByteString 2
y <- getByteString 3
z <- getRemainingLazyByteString
return (x, y, z)
example1 = runGet getThreeBS "Hello World!" -- ("He", "llo", " World!")另一个相关的功能是Control.Monad.replicateM
replicateM :: Int -> Get a -> Get [a]
example2 = runGet (replicateM 5 getWord8) (ByteString.pack [18, 22, 13, 44, 52, 99]) :: [Word8]https://stackoverflow.com/questions/61381134
复制相似问题