【问题标题】:Elixir reducing a list and adding to a mapElixir 减少列表并添加到地图
【发布时间】:2018-02-27 06:28:09
【问题描述】:

我正在尝试减少列表并将一些数据添加到地图中。 代码是这样的:

map = Enum.reduce(1..1000, %{}, fn(x, accumalator) ->(
            calculate a hash of a string
            if condition is fulfilled do
                Map.put(accumalator, string, hash)
            end    
        )end)

这给了我一个糟糕的地图错误,说 Map.put() 正在接收 put 函数的 nil 值。

我想要做的是:对于所有迭代计算散列,如果满足有关散列的某些条件,则将散列和随机数添加到映射中。所以我希望地图是持久的。我哪里错了? 这个answer 也暗示了同样的事情,但是失败了。

【问题讨论】:

  • 当条件不满足时,您可能希望在 if 中添加 else 条件。如果条件不满足,if 表达式将返回 nil,因为这是函数中的最后一个表达式,所以这就是返回的内容。

标签: functional-programming erlang elixir enumeration


【解决方案1】:

函数返回的值在下一次迭代中成为累加器。在您定义的函数中,如果条件为假,if 返回nil,在下一次迭代中accumulatornil。您需要做的是添加一个else 块并从中返回未修改的accumulator 值。

Enum.reduce(1..1000, %{}, fn(x, accumulator) ->
  ...
  if condition do
    Map.put(accumulator, string, hash)
  else
    accumulator
  end
end)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2021-01-02
    • 2019-11-22
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多