【问题标题】:Elixir, List is not referring to new changes inside Enum.mapElixir,List 不是指 Enum.map 内部的新变化
【发布时间】: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


    【解决方案1】:

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

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

    原创

    |> 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-24
      • 2019-12-02
      • 2018-02-05
      • 1970-01-01
      • 2018-05-31
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多