Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading