Search code examples
syntaxerlang

Erlang won't let me end a function


here's my code for an RPS game. I keep getting a syntax error whenever I try to put "end." and it won't let me end the function. It says syntax error before: 'end'.

-module(project).
-export([rps/0]).

rps() ->
    Computer = rand:uniform(3),
    {ok,Player} = io:read("Rock, Paper, or Scissors?"),
    Win = fun() -> io:fwrite("You Win!"),
    Lose = fun() -> io:fwrite("You Lose."),

    % player chooses rock (win, lose)
    if
        Player == "Rock" ->
            if
                Computer == 3 ->
                    Win();
                Computer == 2 ->
                    Lose()
            end;
    % player chooses paper (win, lose)
    if
        Player == "Paper" ->
            if
                Computer == 1 ->
                    Win();
                Computer == 3 ->
                    Lose()
            end;
    % player chooses scissors (win, lose)
    if
        Player == "Scissors" ->
            if
                Computer == 2 ->
                    Win();
                Computer == 1 ->
                    Lose()
            end;
end.  <--------- (this is where error occurs)
                

Solution

  • There were a few mistakes here:

    • fun without "end" (x2) Win = fun() -> io:fwrite("You Win!") end,
    • if-syntax

    correct code:

    -module(project).
    -export([rps/0]).
    
    rps() ->
        Computer = rand:uniform(3),
        {ok,Player} = io:read("Rock, Paper, or Scissors?"),
        Win = fun() -> io:fwrite("You Win!") end,
        Lose = fun() -> io:fwrite("You Lose.") end,
    
        % player chooses rock (win, lose)
        if
            Player == "Rock" ->
                if
                    Computer == 3 ->
                        Win();
                    Computer == 2 ->
                        Lose()
                end;
        % player chooses paper (win, lose)
            Player == "Paper" ->
                if
                    Computer == 1 ->
                        Win();
                    Computer == 3 ->
                        Lose()
                end;
        % player chooses scissors (win, lose)
            Player == "Scissors" ->
                if
                    Computer == 2 ->
                        Win();
                    Computer == 1 ->
                        Lose()
                end
        end.