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.
getA :: Binary -> Maybe (Integer, Binary, Binary)
getA << a:24:Big-Integer , b:4:Binary-Little , c:3:Binary >> = Just (a,b,c)
getA _ = Nothing
> getA <<0,0,1,"aaaa","bbb">>
{'Just',{1,<<"aaaa">>,<<"bbb">>}}
> getA <<0,0,1,"aaaa","bb">>
{'Nothing'}
getB :: Binary -> Maybe (Integer, Binary, Binary)
getB << a:24:Big-Integer , b:4:Binary-Little , c:Binary >> = Just (a,b,c)
getB _ = Nothing
> getB <<0,0,1,"aaaa">>
{'Just',{1,<<"aaaa">>,<<>>}}
> getB <<0,0,1,"aaaa","bbbbbbbbb">>
{'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.
当前内容版权归 hamler-lang 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 hamler-lang .