user2878641
user2878641

Reputation:

How can i count elements of a tuple in Haskell?

So i've got a list of tuples like this one :

xs = [("a","b"),("a","c"),("b","d")

and i want a function that counts the number of times a certain value appears in the first position of the tuple. If i used the list xs and the letter 'a', it would return the value 2, because the letter 'a' appears two times in the first position of the tuple. This function shouldn't be recursive.

So what i've got is this:

f xs = (fst $ unzip xs) / length(xs)

Now i have all the elements down on a list. this would be easy if it was recursive, but if i don't want it that way, how can i do it ?

Upvotes: 2

Views: 1694

Answers (2)

Lee
Lee

Reputation: 144136

If you map the first elements into a list find all occurences of your value and count the length of the resulting list:

countOccurences :: Eq a => a -> [(a, b)] -> Int
countOccurences e = length . filter ((==)e) . map fst

Upvotes: 2

daniel gratzer
daniel gratzer

Reputation: 53881

If we're not using recursion, we need to use some higher order functions. In particular, filter looks helpful, it removes elements who don't satisfy some condition.

Well if we use filter we can get a list of all elements with the first element being the correct thing.

 count :: Eq a => [(a, b)] -> Int
 count x = length . filter ((== x) . fst)

I suppose since you're studying, you should work to understand some folds, start with

count x = foldr step 0
  where step (a, b) r | a == x = 1 + r
                      | otherwise = r

Upvotes: 4

Related Questions