我可以用Elixir或者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
Haskell的库。我还没有在它中找到相应的功能- https:/hackage.haskell.orgpackagebinary-0.10.0.0docsData-Binary-Get.html#t:Get
在Haskell中是否有办法做同样的事情,特别是在 binary
库?
解决方案:
在Haskell中的等价特征 binary
是 的 getByteString
功能.
getByteString :: Int -> Get ByteString
getByteString 6 :: Get ByteString
example = runGet (getByteString 6) "my binary string" :: ByteString
使用do-notation来编写 Get
解析器。还有 getRemainingLazyByteString
来获取其余的bytestring,但要注意的是,虽然它对ElixirErlang风格的解析很有用,但在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]