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