[erlang-questions] Pattern matching in function calls

Dave Challis dsc@REDACTED
Thu Apr 14 12:48:59 CEST 2011


Hi Robby,
Yup, I agree completely :)

My question was mostly prompted by a blog post 
(http://ppolv.wordpress.com/2008/02/25/parsing-csv-in-erlang/) on 
parsing CSV in erlang.

The do_parse function there has a dozen items which search binaries and 
check state, which made me wonder whether swapping the argument order 
round would make any difference at all.

Cheers,
Dave

On 13/04/11 19:44, Robert Raschke wrote:
> Hi Dave,
>
> probably not quite the answer you were looking for, but aim for
> readability first (that's usually already hard enough :-). Only
> compromise that if something is measurably too slow.
>
> In the example you give, it doesn't appear to make any big difference
> for readability, but I assume your real code is a bit more
> "interesting"?
>
> Robby
>
>
> On 4/13/11, Dave Challis<dsc@REDACTED>  wrote:
>> 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
>> clause?
>>
>> 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
>> dsc@REDACTED
>> _______________________________________________
>> erlang-questions mailing list
>> erlang-questions@REDACTED
>> http://erlang.org/mailman/listinfo/erlang-questions
>>


-- 
Dave Challis
dsc@REDACTED



More information about the erlang-questions mailing list