Question

How do you pattern match a bitstring that equals 0 in erlang? In other words patterns of the form:

<<0:17>>
<<0:1>>
<<0:N>>

This is for defining a function.

Thanks

Was it helpful?

Solution

Here is a workaround, I hope it helps:

-module(lab).
-compile(export_all).

is_zero_bitstring(BitString) ->
    Size = erlang:bit_size(BitString),
    <<0:Size>> =:= BitString.

Run it from within the Erlang shell:

1> c(lab).
{ok,lab}
2> lab:is_zero_bitstring(<<0:17>>).
true
3> lab:is_zero_bitstring(<<0:1>>). 
true
4> lab:is_zero_bitstring(<<0:123456>>).  
true
5> lab:is_zero_bitstring(<<7>>).   
false

OTHER TIPS

Is it possible this is what you want?

1> A = <<0:17>>.
<<0,0,0:1>>
2> B = <<0:1>>.
<<0:1>>
3>  C = <<0:3>>.
<<0:3>>
4> F = fun(<<0:17, 0:1, Rest/bitstring>>) -> ok end.
#Fun<erl_eval.6.82930912>
5> F(<<A/bitstring, B/bitstring, C/bitstring>>).
ok
6> F(<<A/bitstring, B/bitstring, C/bitstring, 0:5>>).
ok
7>

The fun will match 17 bits in 0, 1 bit in 0, and the following (N length) in 0. in #5, it is tested with 3 additional bits in 0, and in #6 with 5 more (8 zeroed bits in total)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top