【问题标题】:Pattern matching / deconstruction of binaries and bitstrings in Haskell that's similiar to the one of Elixir/ErlangHaskell 中二进制文件和位串的模式匹配/解构,类似于 Elixir/Erlang 的一种
【发布时间】:2020-06-10 07:17:27
【问题描述】:

在 Elixir/Erlang 中,可以对二进制文件和位串进行这种模式匹配/解构:

  def func1(my_data) do
      <<
        1,
        44,
        a::little-32,
        b::little-64, 
        c, 
        d::64-little, 
        e::32-little-float, 
        rest::binary
      >> = my_data

      # using a, b, c, d, e, rest 

   end

我还没有在 Haskell 中找到这样做的方法。 Haskell 有开箱即用的容量吗?还是需要使用一些第三方库?

【问题讨论】:

  • 您可以使用解析器库之一编写解析器,例如 parsec 或 attoparsec。从ByteString 中解析位需要一些工作,但我已经完成了。
  • @BobDalgleish 没有回答我的问题

标签: string haskell erlang elixir binary-data


【解决方案1】:

没有开箱即用的东西,但类似的东西可以作为具有模式同义词的库来实现,所以它看起来像这样:

-- For some definition of (:.)
case myData of
  (1 :: Word8) :.
    (44 :: Word8) :.
    (a :: Little32) :.
    (b :: Little64) :.
    (c :: Word8) :.
    (d :: Little64) :.
    (e :: LittleFloat32) :.
    rest ->
    {- using a, b, c, d, e, rest -}

完整要点https://gist.github.com/Lysxia/8ee6b9debd613b988023d5a0a8dfd9cc

在 Haskell 中,我们通常更喜欢 binary package 这样的解析器组合库。

【讨论】:

  • 你的答案中myData的类型是什么?
  • 你从哪里得到LittleFloat32Little64
  • For some definition of (:.) 是什么?
  • myDatarest 将是 ByteString。其他一切都需要定义。
  • 这就是我最初的问题 - 如何定义它们?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
  • 1970-01-01
  • 2020-04-23
  • 2013-06-25
  • 2012-07-03
  • 2011-08-14
  • 2013-01-04
相关资源
最近更新 更多