Elixir equivalent of a for loop that count number of occurences when condition is satisfied

Advertisements

I try to do the following thing in Elixir that can be achieved in Python:

sum = 0
for elem in list:
  if elem >= 5:
    sum += 1

For example: I want to return the number 3 given the list [0, 5, 8, 3, 10]

This is what I did in Elixir (this is not working yet):

    cond do
          Enum.empty?(list) -> 0
          length(list) == 1 -> if List.first(list) >= 5 do 1 else 0 end
          true -> 
            Enum.reduce(list, 0, fn x, acc -> if x >= 5 do acc + 1 end end)
          end
    end

I get the following error: ** (ArithmeticError) bad argument in arithmetic expression: nil + 1

Edit:

Found it!
The problem was that I didn’t return any value when x < 5, resulting of no value passed to acc therefore acc was nil. This code below works:

cond do
      Enum.empty?(list) -> 0
      length(list) == 1 -> if List.first(list) >= 5 do 1 else 0 end
      true -> 
        Enum.reduce(list, 0, fn x, acc -> if x >= 5 do acc + 1 else acc + 0 end end)
      end
end

>Solution :

In the reduce function, you forgot to tell what to do when the number is 5 or less:

list = [0, 5, 8, 3, 10]
Enum.reduce(list, 0, fn num, acc -> if num >= 5, do: acc + 1, else: acc end)

Leave a ReplyCancel reply