tarin
tarin

Reputation: 25

Pattern matching / deconstruction of binaries and bitstrings in Haskell that's similiar to the one of Elixir/Erlang

In Elixir/Erlang one can do this kind of pattern matching / deconstruction over binaries and bitstrings:

  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

I've not found a way to do that in Haskell. Is there any out of the box capacity of Haskell? Or will utilizing some third-party library be required?

Upvotes: 2

Views: 294

Answers (1)

Li-yao Xia
Li-yao Xia

Reputation: 33439

There's no such thing out of the box, but something similar can be implemented as a library with pattern synonyms, so it would look like this:

-- 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 -}

Full gist https://gist.github.com/Lysxia/8ee6b9debd613b988023d5a0a8dfd9cc

In Haskell we usually prefer parser combinator libraries like the binary package.

Upvotes: 4

Related Questions