2014-02-23 74 views
1

這可能是一個愚蠢的問題,但我已經花了四個小時在我發佈之前指出問題所在。haskell定義新類型

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. 

謝謝!!

回答

6

你的類型

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 

(您應該將函數體與其類型聲明對齊,但只要它縮進就可以開始新部分)。

3

您需要使用Film構造函數:[Film "Blade Runner" "Ridley Scott" 1982]。另外,我想你想要:而不是+:的參數也需要與當前的參數進行交換。