Functional programming 减少列表并添加到地图的长生不老药

Functional programming 减少列表并添加到地图的长生不老药,functional-programming,erlang,elixir,enumeration,Functional Programming,Erlang,Elixir,Enumeration,我试图减少一个列表,并将一些数据添加到地图中。 代码如下所示: 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

我试图减少一个列表,并将一些数据添加到地图中。 代码如下所示:

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

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

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

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

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

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

当条件未满足时,您可能需要在if中使用else条件。如果条件不满足,if表达式将返回
nil
,因为这是函数中的最后一个表达式,所以返回的就是这个表达式。如果条件不满足,您可能需要if中的else条件。如果不满足条件,if表达式将返回
nil
,因为这是函数中的最后一个表达式,所以返回的就是这个表达式。