【发布时间】:2018-02-17 12:20:02
【问题描述】:
我在长生不老药中添加了一个列表。并尝试使用新索引访问其元素 Enum.map。但我无法访问附加到列表中的较新元素。虽然 IO.inspect 显示它已经添加,但如果我在 Enum.map 内部检查,我会得到旧列表。
对于下面的灵药代码:
list = [0, 1, 2, 3, 4]
add = [5, 6, 7, 8]
data = list + add
data
|> Enum.with_index(0)
|> Enum.map(fn {k, v} -> %{:current => k, :next => list |> Enum.at(v + 1)} end)
|> IO.inspect()
输出
[
%{current: 0, next: 1},
%{current: 1, next: 2},
%{current: 2, next: 3},
%{current: 3, next: 4},
%{current: 4, next: nil},
%{current: 5, next: nil},
%{current: 6, next: nil},
%{current: 7, next: nil},
%{current: 8, next: nil}
]
预期输出
[
%{current: 0, next: 1},
%{current: 1, next: 2},
%{current: 2, next: 3},
%{current: 3, next: 4},
%{current: 4, next: 5},
%{current: 5, next: 6},
%{current: 6, next: 7},
%{current: 7, next: 8},
%{current: 8, next: nil}
]
如何通过我的给定代码获得预期的输出,为什么会这样?
【问题讨论】:
标签: list dictionary enums elixir