Erlang异常错误:在评估if表达式时未找到真正的分支

时间:2017-11-20 10:33:17

标签: erlang

我不太了解erlang,在过去的几个小时里,我一直在寻找解决方法,但我找不到任何好的If语句示例。

我试图使用递归功能将光盘从一个河内塔移动到另一个河内塔。但是,在评估if表达式时,我得到了"没有找到真正的分支"。我理解在某处需要true ->

-module(hanoi).

-export([main/1]).

%% Create Towers
main(NumDiscs) ->
    TowerA = create_tower(NumDiscs),
    TowerB = [],
    TowerC = [],
    display_towers(TowerA,TowerB,TowerC),
    solve(NumDiscs,TowerA,TowerB,TowerC).

%% Add the number of discs inputted to the first tower  
create_tower(0) -> [];

create_tower(NumDiscs) when NumDiscs > 0 ->
    [NumDiscs] ++ create_tower(NumDiscs - 1).

%% Display all towers
display_towers(A,B,C) ->
    io:format("-------------------------\n"),
    io:format("Tower A: ~p\n",[A]),
    io:format("Tower B: ~p\n",[B]),
    io:format("Tower C: ~p\n",[C]).


solve(Disc,TowA,TowB,TowC) ->
if Disc > 0 ->
    solve(Disc - 1,TowA,TowB,TowC),
    TowBNew = [lists:last(TowA)],
    TowCNew = [lists:append(TowC,TowBNew)],
    TowANew = [lists:sublist(TowA,length(TowA) - 1)],
    display_towers(TowANew,TowB,TowCNew),
    solve(Disc - 1,TowANew,TowCNew,TowB)
end.

2 个答案:

答案 0 :(得分:3)

Erlang 中的if表达式必须具有一个评估为true的分支。我猜测Disc > 0为假时会抛出错误。您需要在其中添加true ->子句:

solve(Disc,TowA,TowB,TowC) ->
  if Disc > 0 ->
    solve(Disc - 1,TowA,TowB,TowC),
    TowBNew = [lists:last(TowA)],
    TowCNew = [lists:append(TowC,TowBNew)],
    TowANew = [lists:sublist(TowA,length(TowA) - 1)],
    display_towers(TowANew,TowB,TowCNew),
    solve(Disc - 1,TowANew,TowCNew,TowB); % <- note the ';'
  true ->
    % do something here
end.

答案 1 :(得分:0)

这是我很久以前的代码。希望这可以帮到你:

main(N)->
    towerhanoi(N, a, b, c).
towerhanoi(N, A, C, B)->
    case N of
        1 ->
            change(N, A, C);
        _ ->
            towerhanoi(N-1, A, B, C),
            change(N, A, C),
            towerhanoi(N-1 , B, C, A)
    end.
change(N, A, C)->
    io:format("change disc ~p from tower ~p to tower ~p~n", [N, A, C]).