Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: elegant tuple_to_list/1

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. :)

like image 739
Zakum Avatar asked Apr 25 '13 17:04

Zakum


People also ask

How do I add to a list in Erlang?

In Elixir and Erlang we use `list ++ [elem]` to append elements.

How do I find the length of a list in Erlang?

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).


2 Answers

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.

like image 161
ppolv Avatar answered Sep 19 '22 20:09

ppolv


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]).
like image 44
Hynek -Pichi- Vychodil Avatar answered Sep 17 '22 20:09

Hynek -Pichi- Vychodil