我在这里有这个代码:
-- Types
type Title = String
type Director = String
type Year = Int
type Rating = (String, Int)
-- Define Film type here
type Film = (Title, Director, Year, [Rating])
-- Define database type here
type Database = [Film]
testDatabase :: [Film]
testDatabase = [("Casino Royale", "Martin Campbell", 2006,
[("Garry",-8),("Dave", 0)]), ("Blade Runner", "Ridley Scott", 1982,
[("Amy",5)]), ("The Fly", "David Cronenberg", 1986, [("Fred",7)])]
displayFilmsuser :: String -> Database -> String
displayFilmsuser user database = displayuserFilms (filter (isuser user) database)
isuser:: String -> Film -> Bool
isuser user (t,d,y,r)
| length (filter ((== user).fst) r) > 0 = True
| otherwise = False
displayuserFilm :: Film -> String
displayuserFilm (title, director, year, rating) = "\nTitle: " ++ title ++ "\nRating: " ++ show (filter ((== user).fst) rating) ++ "\n"
displayuserFilms :: Database -> String
displayuserFilms database = concat(map displayuserFilm database )
如何组合这些功能并获得如下的输出:
标题:Casine Royale 评分:4
我可以获得如下输出: 标题:皇家赌场 评级:[(“Garry”, - 8),(“Dave”,0)]
当我将函数displayFilmsuser“Garry”testDatabase作为输入时,我需要 获取用户评级的电影标题和用户评分的费率。 我真的迷失在那里。你能提供一些线索吗?
答案 0 :(得分:1)
抱歉,误解了你。
然后我会通过lookup
displayUserRating :: String -> Film -> (String, Maybe Int)
displayUserRating s (t,d,y,rs) = (t, lookup s rs)
这是你的第一部电影的结果:
displayUserRating "Garry" (head testDatabase)
=("Casino Royale", Just (-8))
此处Maybe
很不错,因为有了它,您可以识别用户是否已评级。
对于其他电影,它会得到(FilmTitle, Nothing)
(加里没有评价任何其他电影)
对于整个数据库:
displayUserRatings :: String -> Database -> [(Title,Int)]
displayUserRatings s d = let ratings = map (displayUserRating s) d
in [(t,fromJust r) | (t,r) <- ratings, r /=Nothing]
where
fromJust (Just a) = a
在这里你只获得那些实际上被s(“Garry”)评级的电影,如果没有,它们就会被过滤掉(通过r /= Nothing
)。因此,使用函数fromJust
是安全的,因为我们知道,r必须是Just Int