InfiniteDonuts
InfiniteDonuts

Reputation: 21

Erlang compiler keeps throwing strange syntax error

So, I am making a tic-tac-toe game in Erlang and it keeps throwing a syntax error and I don't know why. It happens in the function to check if X wins. Here's the code:

checkX(["xxx" | _]) -> true;
checkX([_ | ["xxx" | _]]) -> true;
checkX([_ | [_ | ["xxx" | _]]]) -> true;
checkX(Board) ->
    if 
        xy(Board, {0, 0}) == 120 and xy(Board, {0, 1}) == 120 and xy(Board, {0, 2}) == 120 -> true;

        xy(Board, {1, 0}) == 120 and xy(Board, {1, 1}) == 120 and xy(Board, {1, 2}) == 120 -> true;

        xy(Board, {2, 0}) == 120 and xy(Board, {2, 1}) == 120 and xy(Board, {2, 2}) == 120 -> true;

        xy(Board, {0, 0}) == 120 and xy(Board, {1, 1}) == 120 and xy(Board, {2, 2}) == 120 -> true;

        xy(Board, {2, 0}) == 120 and xy(Board, {1, 1}) == 120 and xy(Board, {0, 2}) == 120 -> true;

       true -> false

    end.

(xy/2 is a function that takes a board (which is a list of strings) and a tuple and returns the character at the position in the tuple.) It keeps throwing this error when I compile it:

board.erl:68: syntax error before '=='

(line 68 is the first condition in the if statement.)

Anyone know why this is?

Upvotes: 2

Views: 90

Answers (1)

7stud
7stud

Reputation: 48599

and binds tighter than ==. Here are the implicit parentheses in your guard:

xy(Board, {0, 0}) == (120 and xy(Board, {0, 1}))

which is not what you intended. Your whole guard ends up being similar to:

if 
   Board == 2 == 3 -> true;
   true -> false
end

which produces the same error. You can fix the error with some parentheses:

if 
   (Board == 2) == 3 -> true;
   true -> false
end

However, even if you add parentheses to your guard, you will then encounter the next error with your guard. See erlang guards in the docs. To wit, you can't call just any function in a guard--there are only a limited number of functions that can be called in a guard, and the allowed functions are listed in the docs.

I suggest you start with a , instead of and when writing guards, then adjust if you need something else, e.g. andalso.

Upvotes: 4

Related Questions