Erlang: elegant tuple_to_list/1
erlang, functional-programming
Solution
I think your function is ok, and more if your goal is to learn the language. As a matter of style, usually the base case when constructing lists is just the empty list []. So I'd write
tup2list(Tuple) -> tup2list(Tuple, 1, tuple_size(Tuple)).
tup2list(Tuple, Pos, Size) when Pos =< Size ->
[element(Pos,Tuple) | tup2list(Tuple, Pos+1, Size)];
tup2list(_Tuple,_Pos,_Size) -> [].
you can write pretty much the same with list comprehension
[element(I,Tuple) || I <- lists:seq(1,tuple_size(Tuple))].
it will work as expected when the tuple has no elements, as lists:seq(1,0) gives an empty list.
Problem
I'm getting myself introduced to Erlang by Armstrongs "Programming Erlang". One Exercise is to write a reeimplementation of the tuple_to_list/1 BIF. My solution seems rather inelegant to me, especially because of the helper function I use. Is there a more Erlang-ish way of doing this? ``` tup2lis({}) -> []; tup2lis(T) -> tup2list_help(T,1,tuple_size(T)). tup2list_help(T,Size,Size) -> [element(Size,T)]; tup2list_help(T,Pos,Size) -> [element(Pos,T)|tup2list_help(T,Pos+1,Size)]. ``` Thank you very much for your ideas. :)