Iterate through a list and count the no of occurrences in Elixir

I am giving a list and a random value as an input ex: Main.counter([15, 30, 60, 15], 15)
The expected result should be 15, As there are 2 instances of 15 in the list.

I want to achieve this by not using any built in functions.

I want to help in iterating over a list with multiple elements…

Recursion is your friend:

def count([], _), do: 0
def count([x | xs], x), do: 1 + count(xs, x)
def count([_ | xs], x), do: count(xs, x)
2 Likes