eg:
ModuleName.function_name([10,20,20,30], 20)
#⇒ 2
I tried it using Enum but it’s especially said that built-in functions cant be used. Can someone give me a solution?
eg:
ModuleName.function_name([10,20,20,30], 20)
#⇒ 2
I tried it using Enum but it’s especially said that built-in functions cant be used. Can someone give me a solution?
A simple and idiomatic way would rely on Enum.count/2:
iex> Enum.count([10,20,20,30], & &1 == 20)
2
If you want to avoid relying on built-in functions, you need to write your own recursive function:
def count_occurrences(list, value), do: do_count_occurrences(list, value, 0)
defp do_count_occurrences([], _value, acc), do: acc
defp do_count_occurrences([value | tail], value, acc) do
do_count_occurrences(tail, value, acc + 1)
end
defp do_count_occurrences([_head | tail], value, acc) do
do_count_occurrences(tail, value, acc)
end
But the reason we have Enum is to avoid doing this every time :)
For the sake of completeness, here is an idiomatic non-recursive solution with for/1 comprehension.
{list, value} = {[10, 20, 20, 30], 20}
for ^value <- list, reduce: 0, do: (acc -> acc + 1)
#⇒ 2