Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List creation in Erlang

From "Erlang Programming" by Cesarini exercise 3-2

As I go through "Erlang Programming" I get weird list creation issues. From exercise 3-2 I wrote two similar functions.

create( 0 ) -> [];
create( N ) when N > 0 -> [ N | create( N-1 ) ].

reverse_create( 0 ) -> [];
reverse_create( N ) when N > 0 -> [ reverse_create( N-1 ) | N ].

so create(3) generates as I'd expect.

exercise3:create(3).
[3,2,1]

but reverse_create does not generate the list I expect.

exercise3:reverse_create(3).
[[[[]|1]|2]|3]

What do I need to change so that reverse_create(3) returns [1,2,3]? Thanks for explaining.

like image 222
Superpolock Avatar asked Nov 20 '10 07:11

Superpolock


People also ask

How do I split a list in Erlang?

You can use lists:split/2 for this: divide(L, N) -> divide(L, N, []). divide([], _, Acc) -> lists:reverse(Acc); divide(L, N, Acc) when length(L) < N -> lists:reverse([L|Acc]); divide(L, N, Acc) -> {H,T} = lists:split(N, L), divide(T, N, [H|Acc]).

How do I check if a list is empty in Erlang?

This is the function that is called: set_viewer_values(Value, ViewerSet) -> if ViewerSet /= empty_set -> lists:map(fun(ViewerPid) -> ViewerPid ! {self(), set_value, Value} end, ViewerSet) end.

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


1 Answers

reverse_create returns a list and you using that as head element to create the list which is resulting in nested lists. Try this solution:

reverse_create( 0 ) -> [];
reverse_create( N ) when N > 0 -> reverse_create( N-1 ) ++ [N].

EDIT: A much better implementation would be:

reverse_create2(N) -> reverse_create_helper(N, []).

reverse_create_helper(0, Acc) ->
    Acc;
reverse_create_helper(N, Acc) ->
    reverse_create_helper(N-1, [N|Acc]).
like image 86
Chandra Patni Avatar answered Sep 28 '22 17:09

Chandra Patni