0

我正在尝试将 Film 类型更改为数据类型,以便更轻松地订购、保存和加载到文件,我在将函数与正确的参数匹配时遇到问题,使用这些类型要容易得多.

type Rating = (String, Int)
--type Film = (String, String, Int, [Rating])
data Film = Film String String Int [Rating]
         deriving (Show,Ord,Eq, Read)

testDatabase :: [Film]
testDatabase = []

testFilm = ("Test","Test",2012,[("Test",8),("Test",5)])

saveToFile :: IO ()
saveToFile = do
    putStrLn "Enter the output filename: "
    name <- getLine
    writeFile name (show testDatabase)
    putStrLn "Done"

loadFromFile :: IO ()
loadFromFile = do
    putStrLn "Enter the input filename: "
    name <- getLine
    contents <- readFile name
    let testDatabase = length contents `seq` (read contents :: [Film])
    putStrLn formatDatabase
    putStrLn "Done"


average xs = realToFrac (sum xs) / genericLength xs 

addFilm :: String -> String -> Int -> [Film] -> [Film]
addFilm title director year db = db ++ Film title director year []

filmsByDirector :: String -> [Film]
filmsByDirector name = filter (\(a,_,_,_) -> a == name) testDatabase

filmsByRating :: Float -> [Film]
filmsByRating rating = filter (\(_,_,_,a) -> filmRating a > rating) testDatabase

filmsByYear :: Int -> [Film]
filmsByYear year = filter (\(_,_,a,_) -> a == year) testDatabase

filmRating :: [(String,Int)] -> Float
filmRating ratings = average (map snd ratings)

formatString :: Film -> String
formatString (dir, film, year, rat) = printf "\n\nDirector: %s \nFilm Name: %s \nYear: %s \nRating: %4.2f" (show dir) (show film) (show year) (filmRating rat)

formattedByYear :: Int -> String
formattedByYear year = concatMap formatString $ filmsByYear year

formattedByDirector :: String -> String
formattedByDirector dir = concatMap formatString $ filmsByDirector dir

formatDatabase = concatMap formatString $ testDatabase
4

1 回答 1

7

没有什么需要改变的,而不是

filmsByDirector name = filter (\(a,_,_,_) -> a == name) testDatabase

在你使用(,,,)模式的构造函数的地方,你使用Film构造函数

filmsByDirector name = filter (\(Film a _ _ _) -> a == name) testDatabase

对于其他功能也是如此。

但是,使用命名字段(或记录)语法并定义要方便得多

data Film = Film { director, title :: String, year :: Int, ratings :: [Rating] }

然后函数将很简单

filmsByDirector name = filter ((name ==) . director) testDatabase

或者,如果您对无点样式感到不舒服

filmsByDirector name = filter (\f -> director f == name) testDatabase

对于关于Filmvs [Film]in的错误addFilm,您必须将最后一部电影包装成[],

addFilm title director year db = db ++ [Film title director year []]
于 2012-05-01T11:04:49.953 回答