[erlang-questions] Construct and match binaries

Olav Frengstad olav@REDACTED
Tue Nov 6 23:42:32 CET 2012


Sorry, this should have gone to the list:

Hey,

I'm trying to use a second variable as a guard for a binary match:

1> F = fun(<<A, $:, B>>, {A, B}) -> ok; (_,_) -> fail end.
#Fun<erl_eval.12.82930912>
2> F(<<"a:b">>, {<<$a>>, <<$b>>}).
fail

After some more digging [1] I do believe this is not possible without
an actual guard expression similar to this:

fun(Bin, {A, B}) when Bin == <<A/binary, $:, B/binary>> -> ok end.

I'm still interested in knowing more about why my first example is not working

Cheers,
Olav

2012/11/6, Jayson Barley <jayson.barley@REDACTED>:
> Switch the match around and it works.
> 1> A = <<$a>>.
> <<"a">>
> 2> B = <<$b>>.
> <<"b">>
> 3> <<"a:b">> = <<A/binary, $:, B/binary>>.
> <<"a:b">>
>
> If I understand the way it works correctly you are attempting to assign the
> right side to the left side in your example. If I am wrong I am sure one of
> the smarter Erlangers will flog me.
>
> Jayson
>
>
> On Tue, Nov 6, 2012 at 2:16 PM, Olav Frengstad <olav@REDACTED> wrote:
>
>> Hey,
>>
>> I'm trying to wrap my head around a problem I have with constructing
>> and matching a binary.
>>
>> Take the following example (will fail with "a binary field without
>> size is only allowed at the end of a binary pattern"):
>>
>> 2> A = <<$a>>,  B = <<$b>>,
>> 2> <<A/binary, $:, B/binary>> = <<"a:b">>.
>> * 2: a binary field without size is only allowed at the end of a binary
>> pattern
>>
>> Using size specification yields the expected result:
>> 3> <<A:1/binary, $:, B:1/binary>> = <<"a:b">>.
>> <<"a:b">>
>>
>> Even equality checks works:
>> 4> <<A/binary, $:, B/binary>> == <<"a:b">>.
>> true
>>
>> I would assume that the size of the binary is known when performing
>> construction and therefore the first example should work (considering
>> <<X/binary,...>> equality checks works).
>>
>> Can anyone shed some light on what's happening here?
>>
>> Cheers,
>> Olav
>> _______________________________________________
>> erlang-questions mailing list
>> erlang-questions@REDACTED
>> http://erlang.org/mailman/listinfo/erlang-questions
>>
>


-- 
Med Vennlig Hilsen
Olav Frengstad

Systemutvikler // FWT
+47 920 42 090



More information about the erlang-questions mailing list