Elixir,List不是指Enum.map中的新变化

时间:2018-02-17 04:17:38

标签: list dictionary enums elixir

我在elixir中添加了一个列表。并尝试使用新索引访问其元素Enum.map。但是我无法访问附加到列表中的较新元素。虽然IO.inspect节目显示它已经添加但是如果我在Enum.map中检查我得到旧列表。

以下elixir代码:

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}
]

如何通过我的代码获得预期的输出,为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

抱歉这是一个愚蠢的错误。

而不是列表我需要输入这样的数据:

  

原始

|> Enum.map(fn {k, v} -> %{:current => k, :next => list |> Enum.at(v + 1)} end)
  

校正

|> Enum.map(fn {k, v} -> %{:current => k, :next => data |> Enum.at(v + 1)} end)