Working with bytesting the way Elixir and Erlang can do

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

  def func1(my_data) do
      <<
        15,
        14,
        a::little-64,
        b::little-16, 
        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 OCaml. Is there such out of the box capacity? Or is utilizing some third-party library required?

You can use the bitstring module, which allows you to write patterns in a similar style:

let func1 my_data =
  match%bitstring my_data with
      {|
        _ : 15;
        _ : 14;
        a : 64 : littleendian;
        b : 16 : littleendian;
        c : 64 : littleendian;
        d : 64 : littleendian;
        e : 32 : littleendian |} -> (a,b,c,d,e)
3 Likes