我的Elixir递归函数返回列表列表,而不是简单的列表
我是,根据链接的书籍(第64页),以下功能:我的Elixir递归函数返回列表列表,而不是简单的列表,elixir,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, [2
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]?这行有一个小错误:
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, []]]]
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, []]]]
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]
哦,兄弟-愚蠢的小语法错误。现在一切都有意义了。顺便说一句,如果我可以补充一下,我收到我(显然很愚蠢)问题答案的速度让我想起了我第一次学习Python的时候——在它成为时尚之前——当时社区真的反应迅速。对长生不老药非常兴奋!如果你想与社区取得更多联系,一定要查看Slack中的Elixir频道和新Elixir论坛():)