我 learning Elixir ,并根据链接的书籍(第64页),以下功能:
defmodule MyList do
def square([]), do: []
def square([ head | tail ]), do: [ head*head, square(tail) ]
end
的行为应如下:
MyList.square [4, 5, 6]
[16, 25, 36]
但是当我将它插入Ubuntu上的Elixir 1.2.0安装时,我得到了:
MyList.square [4, 5, 6]
[16, [25, [36, []]]]
这里发生了什么?我错了还是这本书错了?
如何进入简单[16,25,36]?
答案 0 :(得分:5)
此行中有一个小错误:
def square([ head | tail ]), do: [ head*head, square(tail) ]
如果我们在每一步都递归,那么输出是:
square([4, 5, 6])
[16, square([5, 6])]
[16, [25, square([6])]]
[16, [25, [36, square([])]]]
[16, [25, [36, []]]]
你想:
def square([ head | tail ]), do: [ head*head | square(tail) ]
如果我们在每一步都递归,那么输出是:
square([4, 5, 6])
[16 | square([5, 6])]
[16 | [25 | square([6])]]
[16 | [25 | [36 | square([])]]]
[16 | [25 | [36 | []]]]
在iex中尝试这个:
iex(3)> [16 | [25 | [36 | []]]]
[16, 25, 36]