Reputation: 5417
I'm required to write my own tuple_to_list()
function (yes, from the book) and came up with this in my erl
file:
%% Our very own tuple_to_list function! %%
% First, the accumulator function
my_tuple_to_list_acc(T, L) -> [element(1, T) | L];
my_tuple_to_list_acc({}, L) -> L;
% Finally, the public face of the function
my_tuple_to_list(T) -> my_tuple_to_list_acc(T, []).
When I compile this, however, I get the following error in the shell:
28> c(lib_misc).
lib_misc.erl:34: head mismatch
lib_misc.erl:2: function my_tuple_to_list/1 undefined
error
I have no clue what "head mismatch" there is, and why is the function undefined (I've added it to the module export statement, though I doubt this has much to do with export statements)?
Upvotes: 1
Views: 70
Reputation: 170899
The other answer explains how to fix this, but not the reason. So: ;
after a function definition clause means the next clause continues the definition, just like as for case
and if
branches. head mismatch
means you have function clauses with different names and/or number of arguments in one definition. For the same reason, it is an error to have a clause ending with .
followed by another clause with the same name and argument count.
Changing the order of the clauses is needed for a different reason, not because of the error. Clauses are always checked in order (again, same as for case
and if
) and your first clause already matches any two arguments. So the second would never be used.
Upvotes: 2
Reputation: 26131
When you are interested in working tuple_to_list/1
implementation
1> T2L = fun (T) -> (fun F(_, 0, Acc) -> Acc; F(T, N, Acc) -> F(T, N-1, [element(N, T)|Acc]) end)(T, tuple_size(T), []) end.
#Fun<erl_eval.6.50752066>
2> T2L({}).
[]
3> T2L({a,b,c}).
[a,b,c]
Or in module
my_typle_to_list(_, 0, Acc) -> Acc;
my_typle_to_list(T, N, Acc) ->
my_typle_to_list(T, N-1, [element(N, T)|Acc]).
my_typle_to_list(T) ->
my_typle_to_list(T, tuple_size(T), []).
Note how I use decreasing index for tail recursive function.
Upvotes: 1
Reputation: 1818
Those errors mean that you didn't end definition of my_tuple_to_list_acc/2. You should change order of first two code lines and add dot after them.
my_tuple_to_list_acc({}, L) -> L;
my_tuple_to_list_acc(T, L) -> [element(1, T) | L].
Upvotes: 2