1

I have the following type:

type Rating = (String, Int)
type Film = (String, String, Int, [Rating])

testDatabase :: [Film]
testDatabase = [("Director 1","Film 1",2012,[("TestRat",8)]),("Director 2","Film 2",2,[])]

I need to find out what the average rating of the Director is based on all of their films combined and then all of their ratings combined. I genuinely have no idea how to approach this, I found it hard enough just to get the average of the tuples in the Film let alone work through all of them and do it that way.

My code for working out averages:

filmRating :: [(String,Int)] -> Float
filmRating ratings = average (map snd ratings)

average ratings = realToFrac (sum ratings) / genericLength ratings  
Mat
  • 202,337
  • 40
  • 393
  • 406
JamieB
  • 923
  • 9
  • 30
  • 1
    What are you stuck on? The function to compute the statistics, or how to partition the data? – Don Stewart Apr 18 '12 at 13:21
  • If I could get all of the directors ratings into a single list I could do the rest but I don't know how to partition it into a single list. – JamieB Apr 18 '12 at 13:24
  • Useful functions here are `filter` (to select only films by a particular director) and `concat` (to turn a list of lists of ratings into a list of ratings). – dave4420 Apr 18 '12 at 13:27

1 Answers1

3

There are many useful functions in Data.List for data analysis.

In particular, groupBy is super useful:

> :t groupBy
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

Given an equality function, group a list into buckets.

A function to access the directory:

 > let fst4 (x,_,_,_) = x

Then, sort on the director name, and bucket (group) by that director.

 > let db0 = sortBy (comparing fst4) testDatabase
 > let db1 = groupBy ((==) `on` fst4) db0
 [ [("Director 1","Film 1",2012, [("TestRat",8)])]
 , [("Director 2","Film 2",2    ,[])]
 ]

groupBy is very useful...

Don Stewart
  • 137,316
  • 36
  • 365
  • 468
  • 3
    Note `on` is from `Data.Function` and `comparing` is from `Data.Ord`. – Ben Millwood Apr 18 '12 at 15:58
  • Don thanks for pointing me back to this, I want to find out the average I can already get the films the director is involved in but I can't get the average from all their films. – JamieB May 01 '12 at 14:51