Reputation: 155
I am very new to Erlang and I have a question about this function that returns a list counting down in ones. e.g. [3,2,1]
Why doesn't it work if you change the N-1 to N-2?
I'm looking to get the output to show [7,5,3,1]
-module(create_list).
-export([create_list/1]).
create_list(0) ->
[];
create_list(N) ->
[ N | create_list(N - 1) ].
Upvotes: 1
Views: 1516
Reputation: 815
There is already a function to do this:
lists:seq(From, To, Incr) -> Seq
1> lists:seq(7,1,-2).
[7,5,3,1]
Upvotes: 1
Reputation: 2593
Safer to use positive check:
create_list(N) when N > 0 ->
[N | create_list(N - 2)];
create_list(_) ->
[].
Upvotes: 2
Reputation: 386706
Because no matter how many times you subtract 2 from an odd number, you'll never get zero?
I've never even seen Erlang code before, but I suspect the fix is to add
create_list(1) ->
[ 1 ];
Upvotes: 4