我是 Elixir 新手,正在尝试解决吉他谱问题。 我的代码:
def sumTabs([head|tail], result) do
nextLine = hd(tail)
tail = List.delete(tail, nextLine)
head
|> Enum.with_index
|> Enum.each(fn({x, i}) ->
s = [x <> Enum.at(nextLine, i) |> to_charlist]
IO.inspect s
result = [result | s]
IO.inspect result end)
result
end
我想更新结果,它一开始是一个空列表,但在 Enum.each 函数的每次迭代中,结果都是空的。我认为这是因为匿名函数。
首先,我希望它至少可以使用两行。
输入:
tab = """
e|-7-----7-----7-----7-----5-----3-----3-----2-----0-----0-----|
B|---0-----0-----0-----0-----0-----0-----0-----0-----0-----0---|
G|-----0-----0-----0-----0-----0-----0-----0-----0-----0-----0-|
D|-------------------------------------------------------------|
A|-------------------------------------------------------------|
E|-------------------------------------------------------------|
"""
输出:
['eB']
[[], 'eB']
['||']
[[], '||']
['--']
[[], '--']
['7-']
[[], '7-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['7-']
[[], '7-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['7-']
[[], '7-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['7-']
[[], '7-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['5-']
[[], '5-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['3-']
[[], '3-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['3-']
[[], '3-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['2-']
[[], '2-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['0-']
[[], '0-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['0-']
[[], '0-']
['--']
[[], '--']
['-0']
[[], '-0']
['--']
[[], '--']
['--']
[[], '--']
['--']
[[], '--']
['||']
[[], '||']
sumTabs 函数之前的代码:
defmodule TabPlayer do
def parse(tab) do
String.split(tab, "\n")
|> Enum.map(fn n -> to_string n end)
|> List.delete([])
|> Enum.map(fn n -> String.graphemes n end)
|> sumTabs([])
|> IO.inspect
end
最佳答案
Elixir 中的变量是不可变的。您无法重新分配 Enum.each
内的值并期待外面的情况发生变化。这段代码的作用是创建一个新的 result
持续到匿名函数结束的值。
您可以使用Enum.reduce/3
在这里,返回新的 result
每次迭代的值。假设您的其余逻辑是正确的,以下是如何重写代码以使用 Enum.reduce/3
。请注意,我正在利用 IO.inspect
的事实打印一个值然后返回它。所以IO.inspect(x); x
与 IO.inspect(x)
相同.
def sumTabs([head|tail], result) do
nextLine = hd(tail)
tail = List.delete(tail, nextLine)
head
|> Enum.with_index
|> Enum.reduce([], fn({x, i}, acc) ->
s = IO.inspect [x <> Enum.at(nextLine, i) |> to_charlist]
IO.inspect [s | acc]
end)
# We need to reverse at the end since we're creating a reversed list in
# `Enum.reduce` for efficiency.
|> Enum.reverse
end
关于function - 更新匿名函数 Elixir 中的命名函数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46421739/