不是一个真正的答案,只是一些新手笔记。
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)
。
更新:
我不明白在涉及电影之后如何获得总体平均水平。
让我们从类似的问题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