[erlang-questions] Bit String Comprehension Question

David Mercer <>
Tue Sep 9 21:27:42 CEST 2008


Perfect.  Thank-you.  Thanks also to Grasl Christoph for his assistance.
However, Grasl did write:

> it's well explained in the documentation ('programming-
> examples/constructing binaries and bitstrings')..

Which I do disagree with, somewhat.  I wouldn't call it "well explained" in
that section, at least not in version 5.6.4 of the same.  I read that
section twice before posting my question, and once after I knew the
solution, and I still don't see this case really explained.  I'd suggest a
modification to the documentation, but apparently I am the only nimrod who
couldn't figure out.

Sorry for the line noise, but thanks for the help.

Cheers,

David

> -----Original Message-----
> From: Kostis Sagonas [mailto:]
> Sent: Tuesday, September 09, 2008 11:19
> To: 'erlang-questions'
> Cc: 
> Subject: Re: [erlang-questions] Bit String Comprehension Question
> 
> 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