Haskell 中 Elixir/Erlang 位串的 "binary-size(N)" 模式匹配等价物

Equivalent of "binary-size(N)" pattern matching over a bitstring of Elixir/Erlang, in Haskell

我可以在 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>>

headhead2是我感兴趣的结果变量

我熟悉 Haskell 的 binary 库。我还没有在其中找到等效的功能 - https://hackage.haskell.org/package/binary-0.10.0.0/docs/Data-Binary-Get.html#t:Get

有没有办法在 Haskell 中做同样的事情,特别是在 binary 库中?

Haskell binary 中的等效特征是 the getByteString function

getByteString :: Int -> Get ByteString

getByteString 6 :: Get ByteString

example = runGet (getByteString 6) "my binary string" :: ByteString

使用 do-notation 来组成 Get 解析器。还有 getRemainingLazyByteString 来获取字节串的其余部分,但请注意,虽然它对 Elixir/Erlang-style 解析很有用,但在 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]