我有一个数据类型:
data Film = Film String String Int [Rating]
deriving (Show,Ord,Eq, Read)
样本电影:
("Ridley Scott","Alien",1979,[("Mark",5),("Zoe",3)])
如何在[电影]列表中获得所有影片的平均导演评分?
因此,如果雷德利斯科特有2部电影的平均分数均为5,那么他的整体平均得分为5分。
我只有代码来制作一部电影
filmRating :: [(String,Int)] -> Float
filmRating ratings = average (map snd ratings)
答案 0 :(得分:1)
不是真正的答案,只是一些新手注意事项。
您可以为Director
,Title
和所有其他类型使用类型别名。
type Director = String
type Rate = Double
type Rater = String
type Ratings = [(Rater, Rate)]
type Title = String
type Year = Int
data Film = Film Director Director Year Ratings
deriving (Show,Ord,Eq, Read)
这就是你的film
示例应该是这样的原因:
film = Film "Ridley Scott" "Alien" 1979 [("Mark",5),("Zoe",3)]
如果您有一个名为filmRating
的函数,它应该类似于:: Film -> Rate
:
filmRating :: Film -> Rate
filmRating (Film _ _ _ ratings) = average (map snd ratings)
如何在[电影]列表中获得所有影片的平均导演评分?
你需要像directorsAverageRate :: Director -> [Film] -> Rate
这样的东西。
首先,您需要使用某些Director
函数按:: Film -> Director
值过滤影片。对于此已过滤的列表,您只需获得average . (map filmRating)
的平均费率。
<强> UPD 强>:
我不知道如何在拍摄电影后获得整体平均水平。
让我们从similar question:
中定义average
函数
average :: (Real a, Fractional b) => [a] -> b
average xs = realToFrac (sum xs) / genericLength xs
然后
> let one_film = Film "Ridley Scott" "Alien" 1979 [("Mark",5),("Zoe",3)]
one_film :: Film
> let another_film = Film "Ridley Scott" "Alien2" 2979 [("Mark",4),("Zoe",2)]
another_film :: Film
> let films = [one_film, another_film]
films :: [Film]
> average . (map filmRating) $ films
3.5
it :: Double