这可能是一个愚蠢的问题,但在我发布之前,我花了四个小时来指出问题所在.
data Film = Film {title :: String
,name :: String
,year :: Int}
deriving (Show)
testDatabase :: [Film]
testDatabase = [ ("Blade Runner", "Ridley Scott",1982)]
--(i) Add new film to the database
addFilm :: String -> String -> Int -> [Film] -> [Film]
addFilm title director year film = film + Film title director year
--(ii) Give all film in the database
getFilm :: [Film]
getFilm = testDatabase
Run Code Online (Sandbox Code Playgroud)
我想要做的是定义一个新的类型名称Film,其中包含:电影片名,电影导演和制作年份.
Testdatabase用于存储数据.
addFilm是一个向数据库添加更多电影的功能.
getfilm用于打印出电影列表.
这就是错误的样子.
coursework.hs:21:18:
Couldn't match expected type `Film'
with actual type `([Char], [Char], Integer)'
In the expression: ("Blade Runner", "Ridley Scott", 1982)
In the expression: [("Blade Runner", "Ridley Scott", 1982)]
In an equation for `testDatabase':
testDatabase = [("Blade Runner", "Ridley Scott", 1982)]
coursework.hs:24:43:
Couldn't match expected type `[Film]' with actual type `Film'
In the return type of a call of `Film'
In the second argument of `(+)', namely `Film title director year'
In the expression: film + Film title director year
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)
谢谢!!
你的类型
data Film = Film {title :: String
,name :: String
,year :: Int}
Run Code Online (Sandbox Code Playgroud)
等价于元组类型(String,String,Int),但与它不同.
("Blade Runner", "Ridley Scott",1982) :: (String,String,Int)
Run Code Online (Sandbox Code Playgroud)
但你想要
Film {title = "Blade Runner", name="Ridley Scott",year=1982} :: Film
Run Code Online (Sandbox Code Playgroud)
你写了
addFilm :: String -> String -> Int -> [Film] -> [Film]
addFilm title director year film = film + Film title director year
Run Code Online (Sandbox Code Playgroud)
但+只适用于数字,而不是列表,我们在列表中使用新的东西:,所以'!':"Hello"给出"!Hello",所以你需要
addFilm :: String -> String -> Int -> [Film] -> [Film]
addFilm title director year films
= Film {title=title,name=director,year=year}:films
Run Code Online (Sandbox Code Playgroud)
(你应该将函数体与它的类型声明排成一行,但只要缩进就可以开始一个新的部分.)