views:

125

answers:

2

I am experimenting with bit pattern matching in Erlang:

-module(test).
-export([test/2]).

%test(P,<<X:P,0:1>>) ->
%    X.

test(P,X) ->
    <<Y:P,0:1>> = X,
    Y.

when compiling the commented out version of test/2 i get a complaint that "variable 'P' is unbound". Is there any good reason for not allowing the first version to work the same as the second?

+3  A: 

Because in the commented out version P is a length - for it to work Erlang would need to perform a double match - match the value of the 2nd parameter with a pattern which is undetermined...

The question you are asking in a clause pattern match is "is this the clause for me" - you can't 'pop into the clause' and then back out if it isn't...

In the second example X is bound before the match, you are committed to going into the clause and if <<Y:P,0:1>> don't match X, well crash time!

Gordon Guthrie
A: 

The reason is that arguments to the function are evaluated independent of each other. The correctness of bindings to variables in only checked as a second step.

This means that in your first example P will be unbound when evaluating the second argument, which is against the rules of pattern matching. In contrast, in your second example, P is bound at the time of evaluating the pattern match on the binary.

Zed