erlang 如何为列表创建序列函数?

taor4pac  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(154)

我试图用Erlang创建一个包含整数的列表,如果我传入5,它将创建一个包含[1,2,3,4,5]的列表,这是我目前拥有的代码。
所以我想把这个列表叫做tower1

-module(towers).

-export([create_towers/1]).

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

0kjbasz61#

The code is good, the problem is the syntax

-module(towers).

-export([create_towers/1]).

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

works fine

Eshell V7.1  (abort with ^G)
(emacs@Mac-mini-de-Rodrigo)1> c("/Users/rorra/erlang/towers", [{outdir, "/Users/rorra/erlang/"}]).
{ok,towers}
(emacs@Mac-mini-de-Rodrigo)2> towers:create_towers(0).
[]
(emacs@Mac-mini-de-Rodrigo)3> towers:create_towers(10).
[1,2,3,4,5,6,7,8,9,10]

If you want it to call the list created tower1:

(emacs@Mac-mini-de-Rodrigo)2> Tower1 = towers:create_towers(5).
 [1,2,3,4,5]

notice that all variables starts with upperase, if you want to name the module towers1, change the file name to tower1.erl and add:

-module(tower1).

-export([create_towers/1]).

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

and then you can call towers1:create_towers(N) like:

(emacs@Mac-mini-de-Rodrigo)2> MyVar = tower1:create_towers(5).
[1,2,3,4,5]

相关问题