sirjana luitel
sirjana luitel

Reputation: 43

Is there a way to count the number of occurrences of the first index of a list of tuples

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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

Related Questions