Erlang运动,创建列表 [英] Erlang exercise, creating lists
问题描述
我学习Erlang并从书中练习:
编写一个返回格式列表的函数[1,2,..,N -1,N]。
create(3) - > [1,2,3]。
我有一个解决方案,它是: p>
create(N) - >创建(1,N)。
create(M,M) - > [M];
create(M,N) - > [M |创建(M + 1,N)]。
我经历了十几次,但我根本无法理解第2行发生了什么的解决方案。可以请有人解释一下吗
谢谢。
编辑。
好的,所以我认为我在正确的轨道上了解它。在第2行中,创建了新的列表,其中基本上将1到头和N到尾?如果是,那么在第3行M代表我们在第2行创建的新列表,N代表第1行的输入整数。再次感谢
解决方案的第2行只是递归函数的基本情况。
如果两个数字是相同的create(3,3),那么它将通过递归函数返回一个[3]的列表,并从中创建一个列表。
创建(3) - >创建(1,3) - > [1 |创建(2,3)] - > [2,|创建(3,3)] - > [3] - > [2 | [3]] - > [1 | [2,3]] - > [1,2,3]
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.
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]
这篇关于Erlang运动,创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!