Reputation: 9360
I am learning Erlang using Learn you some erlang
and I am grouping a list in tuples of 3.I do not understand why the book implementation is the following :
group([], Acc) ->Acc
group([A,B,X|Rest], Acc) -> group(Rest, [{A,B,X} | Acc]).
Input
group([],[1,2]).
since it renders the following exception:
exception error: no function clause matching hth:group([],[1,2]) (d:/Erlang/AeRlang/hth.erl, line 15)
Shouldn't it be:
group(Acc,[X,Y,Z|T])->group([{X,Y,Z}|Acc],T);
group(Acc,_)->Acc.
Upvotes: 1
Views: 144
Reputation: 48599
it renders the following exception:
exception error: no function clause matching hth:group([],[1,2]) (d:/Erlang/AeRlang/hth.erl, line 15)
Really? First, let's fix the syntax error:
group([], Acc) ->Acc;
group([A,B,X|Rest], Acc) -> group(Rest, [{A,B,X} | Acc]).
In the 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.
Let's try it:
11> a:group([], [1, 2, 3, 4, 5, 6, 7, 8]).
[{4,5,6},{1,2,3}]
The first definition will throw an error when the number of elements in the list isn't divisible by 3--presumably to alert the user that something is wrong. Your version "fails" silently. It looks like all you did was reverse the arguments in the first version, then in the base case your version matches anything rather than the empty list.
Upvotes: 3