1

我目前有一个包含以下信息的数据库:

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))

它输出每部电影的粉丝数量......

编辑:

我忘了说这个功能需要用户输入一个演员的名字,然后根据电影的粉丝数量和演员出演的电影输出最好的电影。

任何帮助将不胜感激,谢谢!

4

1 回答 1

1

有几个已经预定义的函数 (maximumBycomparing) 可能对您有用。

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
于 2013-04-20T15:57:14.983 回答