[erlang-questions] Pattern matching in function calls

Dave Challis dsc@REDACTED
Wed Apr 13 15:12:36 CEST 2011

On 13/04/11 13:46, Antoine Koener wrote:
> On Apr 13, 2011, at 13:44 , Dave Challis wrote:
>> Does the order of patterns in a function call matter? Are they all
>> tested, or will erlang stop trying to match them once a mismatch has
>> been found?
>> As an example, if I've got:
>> foo(<<SomeLargeBinary>>, a) -> a;
>> foo(<<SomeLargeBinary>>, b) -> b.
>> will the above be any slower than defining:
>> foo(a, <<SomeLargeBinary>>) -> a;
>> foo(b, <<SomeLargeBinary>>) -> b.
>> Will the <<SomeLargeBinary>> attempt to be matched in every case? Is
>> it something worth thinking about, or will the compiler optimise this?
> If the content of <<SomeLargeBinary>> is irrelevant, you can use the '_'
> notation:
> foo(a, _Bin) -> a;
> foo(b, _Bin) -> b;
> Then this is explicit for the reader that you don't want to check _Bin.

Sorry, my example wasn't great, I was more wondering about the cases 
when the binary data is relevant.

So a better example might be:

foo(<<$x,_Rest/binary>>, a) -> a1;
foo(<<$y,_Rest/binary>>, a) -> a2;
foo(<<$z,_Rest/binary>>, a) -> a3;
foo(<<$x,_Rest/binary>>, b) -> b.

If I then called:
foo(<<"x">>, b).

Would erlang perform 4 binary pattern matches until it got to the last 

Or would it optimise things and only perform a single binary match by 
matching on the atoms first?

Or will it always test all arguments in all cases?

Dave Challis

More information about the erlang-questions mailing list