0
votes

I am trying to reduce a list and add some data into a map. The code is something like this:

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)

This is giving me a bad map error saying that Map.put() is receiving a nil value for the put function.

What I want to do is this: For all the iterations calculate the hash and if some condition is fulfilled regarding the hash add the hash and the nonce into the map. So I want the map to be persistent. Where am I going wrong? This answer also suggests the same thing, but is failing.

1
You probably want an else condition in your if for when the condition is not fulfilled. the if expression will return nil if the condition is not met and since that is the last expression in the function, that is what gets returned.Justin Wood

1 Answers

4
votes

The value returned by the function becomes the accumulator in the next iteration. In the function you've defined, if the condition is false, the if returns nil and in the next iteration accumulator is nil. What you need to do is add an else block and return the unmodified accumulator value from that.

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