我目前有一个包含此信息的数据库:
type Title = String
type Actor = String
type Cast = [Actor]
type Year = Int
type Fan = String
type Fans = [Fan]
type Period = (Year, Year)
type Film = (Title, Cast, Year, Fans)
type Database = [Film]
title (t, _, _, _) = t
fans (_, _, _, fs) = fs
year (_, _, y, _) = y
testDatabase :: Database
testDatabase = [("Casino Royale", ["Daniel Craig", "Eva Green", "Judi Dench"], 2006, ["Garry", "Dave", "Zoe", "Kevin", "Emma"]),
("Cowboys & Aliens", ["Harrison Ford", "Daniel Craig", "Olivia Wilde"], 2011, ["Bill", "Jo", "Garry", "Kevin", "Olga", "Liz"]),
("Catch Me If You Can", ["Leonardo DiCaprio", "Tom Hanks"], 2002, ["Zoe", "Heidi", "Jo", "Emma", "Liz", "Sam", "Olga", "Kevin", "Tim"]),
("Mamma Mia!", ["Meryl Streep", "Pierce Brosnan"], 2008, ["Kevin", "Jo", "Liz", "Amy", "Sam", "Zoe"]),
("Saving Private Ryan", ["Tom Hanks", "Matt Damon"], 1998, ["Heidi", "Jo", "Megan", "Olga", "Zoe", "Wally"]),
("Life of Pi" ,["Suraj Sharma"], 2012, ["Kevin", "Olga", "Liz", "Tim", "Zoe", "Paula", "Jo", "Emma"])]
注意:testDatabase包含更多数据,我只包含了一个片段。
现在我的目标是编写一个功能,让我根据粉丝的数量“显示最佳电影”。
我尝试使用'长度粉丝'来输出每部电影的粉丝大小,但我不知道如何绕过然后输出'最佳电影'的标题
以下是displayAllFilms的示例代码:
displayAllFilms' :: [Film] -> String -> String
displayAllFilms' [] filmString = filmString
displayAllFilms' ((title,cast,year,fans):films) filmString =
displayAllFilms' films (filmString ++ "\n" ++ title ++ ", " ++ listStuff cast ", " ++ (show year) ++ ", " ++ show (length fans))
每部电影输出的粉丝数量......
编辑:
我忘了提到这个功能要求用户输入一个演员名字,然后根据电影中的粉丝数量和演员明星输出最佳影片。
非常感谢任何帮助,谢谢!
答案 0 :(得分:1)
有一些已经预定义的功能(maximumBy
和comparing
)可能对您有用。
maximumBy :: (a -> a -> Ordering) -> [a] -> a
comparing :: Ord a => (b -> a) -> b -> b -> Ordering
为了选择粉丝最多的电影你可以写:
import Data.List
import Data.Ord
bestFilm :: Database -> Film
bestFilm = maximumBy $ comparing (length . fans)
可以很容易地翻译成普通英语:“通过比较粉丝列表的长度选择最大的电影”。
请注意,在严重情况下,列表完全不适合表示数据库。您应该使用已排序和/或索引的数据结构。
编辑:
要仅从包含特定演员的电影中选择,您可以先filter
电影。
filmsWithActor :: Actor -> Database -> Database
filmsWithActor actor = filter $ \film -> actor `elem` cast film
cast (_, c, _, _) = c