简体   繁体   中英

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.
Testdatabase is for storing the data.
addFilm is a function for adding more films to the database.
getfilm is for printing out list of films.

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.

("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

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] . Also, I think you want : instead of + . The arguments to : will need to be swapped from what they are currently, as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM