[英]haskell defining new type
This might be a stupid question, but I have spent four hours to finger out what the problem is before I posted this. 这可能是一个愚蠢的问题,但是在发布此问题之前,我花了四个小时来指出问题所在。
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
What I want to do is to define a new type name Film
which contains: film title, film director and year of making. 我想要做的是定义一个新的类型名称Film
包含:电影片名,电影导演和制作一年的。
Testdatabase
is for storing the data. Testdatabase
用于存储数据。
addFilm
is a function for adding more films to the database. addFilm
是用于向数据库中添加更多影片的功能。
getfilm
is for printing out list of films. getfilm
用于打印电影列表。
This is what the error looks like. 这就是错误的样子。
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.
Thanks!! 谢谢!!
Your type 您的类型
data Film = Film {title :: String
,name :: String
,year :: Int}
is equivalent to the tuple type (String,String,Int)
, but not the same as it. 等效于元组类型(String,String,Int)
,但与它不同。
("Blade Runner", "Ridley Scott",1982) :: (String,String,Int)
but you want 但是你想要
Film {title = "Blade Runner", name="Ridley Scott",year=1982} :: Film
You wrote 你写了
addFilm :: String -> String -> Int -> [Film] -> [Film]
addFilm title director year film = film + Film title director year
but +
only works on numbers, not lists, and we put new things in lists using :
, so '!':"Hello"
gives "!Hello"
, so you need 但是+
仅适用于数字,不适用于列表,我们使用:
将新事物添加到列表中,因此'!':"Hello"
给出"!Hello"
,因此您需要
addFilm :: String -> String -> Int -> [Film] -> [Film]
addFilm title director year films
= Film {title=title,name=director,year=year}:films
(You should line up the function body with its type declaration, but it's OK to start a new line part way through as long as it's indented.) (您应该将函数主体与其类型声明对齐,但是也可以在缩进的部分开始新的一行。)
You need to use the Film constructor: [Film "Blade Runner" "Ridley Scott" 1982]
. 您需要使用Film构造函数: [Film "Blade Runner" "Ridley Scott" 1982]
。 Also, I think you want :
instead of +
. 另外,我认为您想要:
而不是+
。 The arguments to :
will need to be swapped from what they are currently, as well. 到的参数:
将需要从交换它们是什么目前,还有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.