[erlang-questions] Bit String Comprehension Question
Kostis Sagonas
kostis@REDACTED
Tue Sep 9 18:18:58 CEST 2008
David Mercer wrote:
> Why does the bit-string comprehension #133 below work whereas #134 is a
> syntax error?
>
> 133> << <<X:N>> || {X,N} <- [{3,5}] >>.
> <<3:5>>
>
> 134> << Bin || Bin <- [<<3:5>>] >>.
> * 1: syntax error before: '||'
In bit stream comprehensions, the elements of the resulting binary have
to have an unambiguously defined size. This means that they have to be
a bit stream *segments*, and the parser requires segments to be enclosed
in << and >>. So, if you want to write the above, you have to write
something like:
<< <<Bin/bits>> || Bin <- [<<3:5>>] >>.
which is just a convenient shorthand for the following expression, which
you can also write:
<< <<Bin:(bit_size(Bin))/bits>> || Bin <- [<<3:5>>] >>.
(This because bit_size(Bin) is the default size for bits type segments.)
If you do not like this default expansion of "take all bits, please" you
are also allowed to take less:
<< <<Bin:2/bits>> || Bin <- [<<3:5>>] >>.
Kostis
More information about the erlang-questions
mailing list