G.M
G.M

Reputation: 663

Erlang exercise, creating lists

I`m learning Erlang and doing exercises from the book:

"Write a function which returns a list of the format [1,2,..,N-1,N]. create(3) -> [1,2,3]."

I have a solution, which is:

create(N) ->   create(1, N).
create (M,M) ->  [M];
create(M,N) -> [M | create(M+1, N)].

I went through it dozen of times, but I simply can`t understand what is happening on line 2 of the solution. Can please somebody explain? Thank you.

EDIT. Ok, so i think I`m on the right track for understanding it. In line 2, the new list is created where basically 1 will go to the Head and N to the Tail? If yes, then on line 3 M stands for new list that we created on line 2, and N stands for the input integer from the line 1? Thanks again.

Upvotes: 1

Views: 460

Answers (2)

Leo Correa
Leo Correa

Reputation: 19839

Line 2 of the solution is simply just the base case of a recursive function.

If the two numbers are the same create(3, 3) then it will return a list of [3] back through the recursive function and building a list out of that.

create(3) -> create(1, 3) -> [1 | create(2, 3)] -> [2, | create(3, 3)] -> [3] -> [2 | [3]] -> [1 | [2, 3]] -> [1, 2, 3]

Upvotes: 2

user2805280
user2805280

Reputation: 11

create (M,M) ->  [M];

That simply means creating a list from M to M, which has only one number, M.

For example,

create (1,1) 

would give you [1], because the list starts at 1 and ends at 1.

Upvotes: 1

Related Questions