列表中组的模式匹配
Pattern matching on groups in list
我正在使用 Learn you some erlang
学习 Erlang,我正在对 3.I 元组中的列表进行分组 不明白为什么本书的实现如下:
group([], Acc) ->Acc
group([A,B,X|Rest], Acc) -> group(Rest, [{A,B,X} | Acc]).
输入
group([],[1,2]).
因为它呈现以下异常:
exception error: no function clause matching
hth:group([],[1,2]) (d:/Erlang/AeRlang/hth.erl, line 15)
不应该是:
group(Acc,[X,Y,Z|T])->group([{X,Y,Z}|Acc],T);
group(Acc,_)->Acc.
it renders the following exception:
exception error: no function clause matching hth:group([],[1,2])
(d:/Erlang/AeRlang/hth.erl, line 15)
真的吗?首先,让我们修复语法错误:
group([], Acc) ->Acc;
group([A,B,X|Rest], Acc) -> group(Rest, [{A,B,X} | Acc]).
在shell:
~/erlang_programs$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V9.3 (abort with ^G)
1> c(a).
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}
2> a:group([], [1, 2]).
[1,2]
Shouldn't it be:
group(Acc,[X,Y,Z|T])->group([{X,Y,Z}|Acc],T);
group(Acc,_)->Acc.
让我们试试看:
11> a:group([], [1, 2, 3, 4, 5, 6, 7, 8]).
[{4,5,6},{1,2,3}]
当列表中的元素数不能被 3 整除时,第一个定义将抛出错误——大概是为了提醒用户出现问题。你的版本"fails"默默。看起来你所做的只是颠倒了第一个版本中的参数,然后在 基本情况下 你的版本匹配任何东西而不是空列表。
我正在使用 Learn you some erlang
学习 Erlang,我正在对 3.I 元组中的列表进行分组 不明白为什么本书的实现如下:
group([], Acc) ->Acc
group([A,B,X|Rest], Acc) -> group(Rest, [{A,B,X} | Acc]).
输入
group([],[1,2]).
因为它呈现以下异常:
exception error: no function clause matching hth:group([],[1,2]) (d:/Erlang/AeRlang/hth.erl, line 15)
不应该是:
group(Acc,[X,Y,Z|T])->group([{X,Y,Z}|Acc],T);
group(Acc,_)->Acc.
it renders the following exception:
exception error: no function clause matching hth:group([],[1,2]) (d:/Erlang/AeRlang/hth.erl, line 15)
真的吗?首先,让我们修复语法错误:
group([], Acc) ->Acc;
group([A,B,X|Rest], Acc) -> group(Rest, [{A,B,X} | Acc]).
在shell:
~/erlang_programs$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V9.3 (abort with ^G)
1> c(a).
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}
2> a:group([], [1, 2]).
[1,2]
Shouldn't it be:
group(Acc,[X,Y,Z|T])->group([{X,Y,Z}|Acc],T); group(Acc,_)->Acc.
让我们试试看:
11> a:group([], [1, 2, 3, 4, 5, 6, 7, 8]).
[{4,5,6},{1,2,3}]
当列表中的元素数不能被 3 整除时,第一个定义将抛出错误——大概是为了提醒用户出现问题。你的版本"fails"默默。看起来你所做的只是颠倒了第一个版本中的参数,然后在 基本情况下 你的版本匹配任何东西而不是空列表。