4

I got this very newb and simple function in erlang:

function_x(L) ->
    X = lists:filter((fun(N)-> N =:= 2 end), L),
    Y = lists:filter((fun(N)-> N =:= 3 end), L),
    LX = length(X),
    LY = length(Y),
    LX == 2 or LY == 2.

Compile the source, and I get this error:

syntax error before: '=='

I pull of one of the expressions from the or clausule and it works. I'm very newb in erlang as you see and really don't understand why this happens if it seems so simple. Any help? Thanks

2 Answers 2

7

According to the operator precedence in Erlang, the precedence of or is higher than that of ==. So your expression as written is treated as

LX == (2 or LY) == 2

which is a syntax error. To fix this, you must use parentheses around each term:

(LX == 2) or (LY == 2).

Alternatively, you can use orelse which has a lower precedence than ==:

LX == 2 orelse LY == 2.
1
  • Thanks! I was loosing my faith in erlang heh :D
    – Cheluis
    Oct 9, 2011 at 15:21
3

For some reason, == and 'or' probably have the same operator precedence, so you need to tell the compiler more exactly what it is you want. You could either write "(LX == 2) or (LY == 2)" or use 'orelse' instead of 'or'.

3
  • Nah, or has a higher precedence than == so the expression is parsed as LX == (2 or LY) == 2, but as == has no associativy, this results in a parse error.
    – nox
    Oct 9, 2011 at 11:05
  • 1
    I'd use orelse here. It is short-circuiting and it is probably a tad faster. Also, there is no reason to evaluate the RHS for the effect. Oct 9, 2011 at 12:28
  • 1
    The fact that the comparison operators aren't associative surprised even me, but of course, it's not the thing you'd write in any sane program, so they might be better off without.
    – RichardC
    Oct 9, 2011 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.