问题
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
回答1:
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...
来源:https://stackoverflow.com/questions/10210225/haskell-selectively-adding-lists