[erlang-questions] Guards?
Douglas Rohrer
drohrer@REDACTED
Tue Apr 5 14:56:33 CEST 2016
What you're missing is operator precedence [1] - "and" takes precedence over "<", so your guard clause ends up looking, to the runtime, like what Bengt pointed out - you have the boolean expression `is_inteteger(X) or is_float(X)` followed by and, followed by X - which is evaluated before the < operator. The evaluation of your guard looks something like this:
X = 1
(((is_integer(1) or is_float(1)) and 1) < 5
(((true) and 1) < 5)
`true and 1` cannot be evaluated (throws an exception, as `and` doesn't take integer arguments). Now, your guard expression threw an exception - what happens then:
"If an arithmetic expression, a Boolean expression, a short-circuit expression, or a call to a guard BIF fails (because of invalid arguments), the entire guard fails. If the guard was part of a guard sequence, the next guard in the sequence (that is, the guard following the next semicolon) is evaluated." [2]
So, your guard ends up not matching - you have no other function clauses, so you have "no function clause matching."
Make sense now?
Doug
[1] http://erlang.org/doc/reference_manual/expressions.html#id84275 <http://erlang.org/doc/reference_manual/expressions.html#id84275>
[2] http://erlang.org/doc/reference_manual/expressions.html#id83710
> On Apr 5, 2016, at 8:38 AM, Kostis Sagonas <kostis@REDACTED> wrote:
>
> On 04/05/2016 02:27 PM, Roberto Ostinelli wrote:
>> I'm a little stumped and I feel I'm missing something sooooooo beginner
>> here.
>>
>> 1> F = fun(X) when (is_integer(X) or is_float(X)) and X < 5 -> ok end.
>> #Fun<erl_eval.6.50752066>
>> 2> F(1).
>> ** exception error: no function clause matching
>> erl_eval:'-inside-an-interpreted-fun-'(1)
>> 3> F2 = fun(X) when (is_integer(X) or is_float(X)) and (X < 5) -> ok end.
>> #Fun<erl_eval.6.50752066>
>> 4> F2(1).
>> ok
>>
>> ...Can some kind soul clarify?
>
> It's a long story. Its short version is that you will have a much better state of mind if you forget the presence of 'or' and 'and' in guards and use ';' and ',' when you can, and 'orelse' and 'andalso' when you cannot (as in your F fun).
>
> 1> F = fun(X) when (is_integer(X) orelse is_float(X)) andalso X < 5 -> ok enD.
> #Fun<erl_eval.6.50752066>
> 2> F(1).
> ok
>
>
> Kostis
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20160405/8d1d237d/attachment.htm>
More information about the erlang-questions
mailing list