【问题标题】:haskell defining new typehaskell 定义新类型
【发布时间】:2014-02-23 00:06:54
【问题描述】:

这可能是一个愚蠢的问题,但在发布此问题之前,我已经花了四个小时找出问题所在。

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

我要做的是定义一个新的类型名称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.

谢谢!!

【问题讨论】:

    标签: haskell


    【解决方案1】:

    你的类型

    data Film = Film {title :: String
                    ,name :: String
                    ,year :: Int}
    

    相当于元组类型(String,String,Int),但又不一样。

    ("Blade Runner", "Ridley Scott",1982) :: (String,String,Int)
    

    但你想要

    Film {title = "Blade Runner", name="Ridley Scott",year=1982} :: Film
    

    你写的

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

    但是+ 仅适用于数字,而不适用于列表,我们使用 : 将新事物放入列表中,所以 '!':"Hello" 给出了 "!Hello",所以你需要

    addFilm :: String -> String -> Int -> [Film] -> [Film]
    addFilm title director year films  
        = Film {title=title,name=director,year=year}:films
    

    (您应该将函数体与其类型声明对齐,但只要缩进就可以在中途开始新行。)

    【讨论】:

      【解决方案2】:

      您需要使用 Film 构造函数:[Film "Blade Runner" "Ridley Scott" 1982]。另外,我认为您想要: 而不是+: 的参数也需要与当前的参数交换。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        • 2012-03-12
        • 1970-01-01
        相关资源
        最近更新 更多