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. :)
In Elixir and Erlang we use `list ++ [elem]` to append elements.
You can use length() to find the length of a list, and can use list comprehensions to filter your list. num(L) -> length([X || X <- L, X < 1]). Working example: % list counter program -module(listcounter).
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.
Your code is good and also idiomatic way how to make this sort of stuff. You can also build this list backward which in this case will be a little bit faster because of tail call but not significant.
tup2list(T) -> tup2list(T, size(T), []).
tup2list(T, 0, Acc) -> Acc;
tup2list(T, N, Acc) -> tup2list(T, N-1, [element(N,T)|Acc]).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With