Binary Patterns

Matching on binaries is just like how it is done in Erlang. Int the following example, we are trying to get a 24-bit integer out of the Binary passed to getA.

  1. getA :: Binary -> Maybe (Integer, Binary, Binary)
  2. getA << a:24:Big-Integer , b:4:Binary-Little , c:3:Binary >> = Just (a,b,c)
  3. getA _ = Nothing
  4. > getA <<0,0,1,"aaaa","bbb">>
  5. {'Just',{1,<<"aaaa">>,<<"bbb">>}}
  6. > getA <<0,0,1,"aaaa","bb">>
  7. {'Nothing'}
  8. getB :: Binary -> Maybe (Integer, Binary, Binary)
  9. getB << a:24:Big-Integer , b:4:Binary-Little , c:Binary >> = Just (a,b,c)
  10. getB _ = Nothing
  11. > getB <<0,0,1,"aaaa">>
  12. {'Just',{1,<<"aaaa">>,<<>>}}
  13. > getB <<0,0,1,"aaaa","bbbbbbbbb">>
  14. {'Just',{1,<<"aaaa">>,<<"bbbbbbbbb">>}}

Big and Little means the endianess in the part we need. Integer or Binary is the type we will give to after we extract the segment. The number of bits of the segment depends on the size of the segment we need and the type we assign. If they type we assign is an Integer then we get exact the same number of the size of bits, which is required to be evenly divisible by 8. If it is a Binary we want, it will need 8 times the size of bits.