Reputation: 43
I am trying to write a function in Haskell that takes in a list of tuples (the first index of each tuple is an int and the second index a char) and an integer and will return the number of occurrences in the first index of each tuple. So far I have:
counter :: Eq a => [a] -> a -> Int
counter [] find = 0
counter ys find = length xs
where xs = [xs | xs <- ys, xs == find]
For example, if I run:
counter [(3,"a"),(4,"b"),(2,"a"), (3, "f"),(3,"t")] 3
This should return 3 since there are 3 tuples in the list where the first index is 3.
Upvotes: 1
Views: 161
Reputation: 476584
You need to unpack the 2-tuple and check the first item, so:
counter :: Eq a => [(a, b)] -> a -> Int
counter ys find = length [ x | (x,_) <- ys, x == find]
or with filter :: (a -> Bool) -> [a] -> [a]
:
counter :: Eq a => [(a, b)] -> a -> Int
counter ys find = length (filter ((find ==) . fst) ys)
Upvotes: 2