Erlang 使用空列表作为保护子句

Erlang 使用空列表作为保护子句,erlang,Erlang,我从erlang开始,从一些简单的练习开始。在这个例子中,我试图计算高斯三角形行。我不明白为什么我会收到这样的警告: Warning: this clause cannot match because a previous clause at line 6 always matches 这个问题与保护条款有关,但对我来说似乎是合法的xD。以下是完整的代码: create_row(Initial)->create_row(Initial,[1]). create_row([First|R

我从erlang开始,从一些简单的练习开始。在这个例子中,我试图计算高斯三角形行。我不明白为什么我会收到这样的警告:

Warning: this clause cannot match because a previous clause at line 6 always matches
这个问题与保护条款有关,但对我来说似乎是合法的xD。以下是完整的代码:

create_row(Initial)->create_row(Initial,[1]).

create_row([First|Rest],Current) -> 
    io:format("rest size: ~w ~n",[Rest]),
    create_row(Rest,lists:append(Current,[First+lists:nth(1, Rest)]));

create_row([_|Rest],Current) when length(Rest)==0 -> lists:append(Current,[1]).

有什么想法吗?

您有两种模式用于
创建行/2
功能,顺序如下:

create_row([First|Rest],Current) ->

模式按顺序匹配。第一种模式将匹配第二种模式执行的所有情况,因此第二种模式将永远不会执行

如果您颠倒了功能顺序,它应该可以工作:

create_row([_|Rest],Current) when length(Rest)==0 -> 
  lists:append(Current,[1]);
create_row([First|Rest],Current) -> 
  io:format("rest size: ~w ~n",[Rest]),
  create_row(Rest,lists:append(Current,[First+lists:nth(1, Rest)])).
现在,第一个函数将只匹配长度为0的函数,第二个函数将匹配其余的函数


请注意,大多数特定功能应位于顶部。

不过,警告消息的原因在的中进行了说明

是效率较低的等价物

create_row([_],Current) ->
hd(Rest)

是效率较低的等价物

create_row([_],Current) ->
hd(Rest)
无论如何,您可能正在寻找:

create_row([]) -> [1];
create_row([H|T])->
    [H | create_row(H, T)].

create_row(X, [H|T]) ->
    [X+H | create_row(H, T)];
create_row(X, []) -> [X].
你在做帕斯卡三角形,对吗

18> test:create_row([]).
[1]
19> test:create_row(v(-1)).
[1,1]
20> test:create_row(v(-1)).
[1,2,1]
21> test:create_row(v(-1)).
[1,3,3,1]
22> test:create_row(v(-1)).
[1,4,6,4,1]
23> test:create_row(v(-1)).
[1,5,10,10,5,1]
24> test:create_row(v(-1)).
[1,6,15,20,15,6,1]
25> test:create_row(v(-1)).
[1,7,21,35,35,21,7,1]
26> test:create_row(v(-1)).
[1,8,28,56,70,56,28,8,1]

顺便说一句,您的代码是O(N^2),因为在累加器的末尾追加了
Current

Ok!!我不知道!!,所以现在大家都有道理了。我认为功能顺序没有任何影响。哇!你的实现很好!!在erlang:)@rdiaz82中我还有很长的路要走。我添加了更高效、更优雅的版本。请注意,
v(-1)
是一个shell命令,它引用了上一个命令的结果。
18> test:create_row([]).
[1]
19> test:create_row(v(-1)).
[1,1]
20> test:create_row(v(-1)).
[1,2,1]
21> test:create_row(v(-1)).
[1,3,3,1]
22> test:create_row(v(-1)).
[1,4,6,4,1]
23> test:create_row(v(-1)).
[1,5,10,10,5,1]
24> test:create_row(v(-1)).
[1,6,15,20,15,6,1]
25> test:create_row(v(-1)).
[1,7,21,35,35,21,7,1]
26> test:create_row(v(-1)).
[1,8,28,56,70,56,28,8,1]