I’m trying to create a list and print it out, counting down from N to 1. This is my attempt:
%% Create a list counting down from N to 1 %%
-module(list).
-export([create_list/1]).
create_list(N) when length(N)<hd(N) ->
lists:append([N],lists:last([N])-1),
create_list(lists:last([N])-1);
create_list(N) ->
N.
This works when N is 1, but otherwise I get this error:
172> list:create_list([2]).
** exception error: an error occurred when evaluating an arithmetic expression
in function list:create_list/1 (list.erl, line 6)
Any help would be appreciated.
The error is
lists:last([N])-1. Since N is an array as your input,lists:last([N])will return N itself. Not a number you expect. And if you see the warning when compiling your code, there is another bug:lists:appendwill not append the element into N itself, but in the return value. In functional programming, the value of a variable cannot be changed.Here’s my implementation: