user17468100
user17468100

Reputation:

counting number of times a key is in map

I have the following code:

type Film = (Fan, Title, Review)
filmRating :: [Film] -> [(Fan, Int)]
filmRating l = undefined

I want to be able to give a list:

[("fan1", "film1", 3), ("fan1", "film2", 3), ("fan3", "film1", 5), ("fan4", "film3", 8)]

Now the function wants me to outout a list with how many films a fan watched. so with the list above, I should get:

[("fan1", 2). ("fan3", 1), ("fan4", 1)]

I need to use map and set so I ended up with this

titlesFan :: (Ord k, Ord a) => [(k, a, c)] -> [(k, [a])]
titlesFan l = Map.fromListWith (++) [(f, [t]) | (f, t, _) <- l]

and I can't seem to be able to get the length as it just gives 1

Upvotes: 1

Views: 97

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152707

The length of a pair is always 1*:

> length (False, "abc")
1

Probably this is what's happening to you, accidentally. Instead, ask for the length of the second part of the tuple:

> length . snd $ (False, "abc")
3

* If you think of (Bool, String) as being a container of Strings, it's clear that there's always exactly one String in that container, which justifies this result. Though of course whether or not you consider the thought of (Bool, String) being a container of Strings to be justified is a different thing entirely...

Upvotes: 2

Related Questions