Erlang不让我结束函数

dzhpxtsq  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(179)

这是我的一个RPS游戏的代码。每当我尝试输入“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)
sirbozc5

sirbozc51#

Artee's answer解释了语法错误发生的位置和方式。让我建议用一种不同的方式来编写它,它可以被认为更“像Erlang-like”一点,并且顺便摆脱了语法错误。
首先,让Computer变量包含计算机的选择,其格式与玩家的相同:

Computer = element(rand:uniform(3), {"Rock", "Paper", "Scissors"}),

然后,创建一个函数,该函数接受玩家的选择和计算机的选择,并返回获胜者:

who_wins("Rock", "Scissors") ->
    player;
who_wins("Rock", "Paper") ->
    computer;
who_wins("Paper", "Scissors") ->
    computer;
who_wins("Paper", "Rock") ->
    player;
who_wins("Scissors", "Rock") ->
    computer;
who_wins("Scissors", "Paper") ->
    player;
who_wins(Same, Same) ->
    tie.

(In最后一个子句,因为我们对两个参数使用相同的变量名,所以只有当参数相同时,此子句才匹配。)
然后,回到rps函数,我们可以将嵌套的if表达式替换为:

case who_wins(Player, Computer) of
    player ->
        Win();
    computer ->
        Lose();
    tie ->
        io:fwrite("It's a tie!")
end.
xxslljrj

xxslljrj2#

这里有几个错误:

  • 没有“end”的乐趣(x2)Win = fun()-〉io:fwrite(“你赢了!”)end,
  • if语法

正确代码:

-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.

相关问题