Reputation: 65
I'm trying to recursively count how many times a given element (number) appears in a list.
For example, equals 2 [1,2,3,2,1,2,3]
should return 3 for the number of times 2 appears in the list.
What i've done so far:
equals :: Integer -> [Integer] -> Int
equals n [] = 0
equals n (x:xs) =
if equals n == x
then 1 + equals n xs
else equals xs
Upvotes: 1
Views: 774
Reputation: 575
You are nearly there. Just keep in mind when you want to call your function and remember to give it all required arguments.
equals :: Integer -> [Integer] -> Int
equals n [] = 0
equals n (x:xs)
| n == x = 1 + equals n xs
| otherwise = equals n xs
Upvotes: 3
Reputation: 70377
You basically have the solution. There's just a few minor typos to squash.
equals :: Integer -> [Integer] -> Int
equals n [] = 0
equals n (x:xs) =
if n == x then
1 + equals n xs
else
equals n xs
In particular, whenever you call equals
, you need to pass it two parameters. So your recursive call should generally look like equals n xs
, not equals xs
. Similarly, your comparison between n
and x
is just that: a comparison. It needn't itself make a recursive call, so it only needs to look like n == x
.
Upvotes: 3