[erlang-questions] Binary match in function head doesn't compile
Jeff Schultz
jws@REDACTED
Sat Oct 27 03:34:39 CEST 2012
On Fri, Oct 26, 2012 at 11:27:06AM -0700, Erik Pearson wrote:
> test(<<Field:Len/binary, Rest/binary>>, Len) ->
> {Len, Field, Rest}.
> does not compile, complaining that "variable 'Len' is unbound", while this
Short answer: Erlang isn't a general constraint solver.
> test(<<Field:2/binary, Rest/binary>>, Field) ->
> {Field, Rest}.
> does. For some reason the compiler doesn't see the Len from the match spec
> in the arguments, but it does see Field. Is that by design?
That depends on what you mean by "see." It actually treats that clause
as if it were something like
test(<<Field:2/binary, Rest/binary>>, Arg2),
Field = Arg2
->
{Field, Rest}.
(Which is not Erlang, but I hope you get the idea.)
And, of course, your problem clause looks like
test(<<Field:Len/binary, Rest/binary>>, Arg2),
Len = Arg2
->
{Len, Field, Rest}.
which makes clear why the compiler sees Len as unbound when used in
the pattern match.
It's obviously easy to re-arrange the data-flow to make this sort of
thing compilable. I wouldn't expect to run across a need for it in
practice though.
Jeff Schultz
More information about the erlang-questions
mailing list