[erlang-questions] Matching binaries and shadowed variables

Anthony Ramine n.oxyde@REDACTED
Fri Nov 29 12:54:27 CET 2013


No, the A in the function clause is fresh and shadows the previous A.

> lists:map(fun (<<A:ASize/binary, _/binary>>) -> match; (_) -> nomatch end, [<<"foobar">>]).
[match]

And if it did not shadow the previous A binding, the closure would return nomatch for <<"nohello">> because it does not begin with hello.

-- 
Anthony Ramine

Le 29 nov. 2013 à 12:37, Ivan Uemlianin <ivan@REDACTED> a écrit :

> You can match A like this:
> 
> > A = <<"hello">>.
> > ASize = size(A).
> > lists:map(fun (<<A:ASize/binary, _/binary>>) -> match;
> >               (_) -> nomatch end,
> >           [<<"hello world">>, <<"nohello">>]).
> > [match,match]
> 
> Ivan
> 
> (Sorry if someone else has replied to this)
> 
> 
> On 27/11/2013 18:56, virtan wrote:
>> Does anybody know why there is a such thing as shadowed variables in Erlang?
>> What was the reason to prevent typical "matching" approach for closures?
>> 
>> It is even more unclear in matching binaries:
>> 
>> 1> A = <<"hello">>, ASize = size(A),
>>       lists:map(
>>           fun (<<A1:ASize/binary, _/binary>>) when A1 == A -> match;
>>                 (_) -> nomatch end,
>>           [<<"hello world">>, <<"nohello">>]).
>> [match,nomatch]
>> 2>
>> 
>> You can't use A instead of A1 (it creates new variable, shadowing outer A),
>> but should use ASize inside the pattern (otherwise you'll get unbound error during compilation).
>> 
> 
> -- 
> ============================================================
> Ivan A. Uemlianin PhD
> Llaisdy
> Speech Technology Research and Development
> 
>                    ivan@REDACTED
>                     www.llaisdy.com
>                         llaisdy.wordpress.com
>              github.com/llaisdy
>                     www.linkedin.com/in/ivanuemlianin
> 
>                        festina lente
> ============================================================
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list