0

I have been wondering why I keep getting the error:

*** Exception: Prelude.read: no parse.

This happens after i go through my code and select option 2.

This is defining Film

type Title      = String
type Director   = String
type Year       = Int
type Rating     = (String, Int)

data Film = Film Title Director Year [(Rating)] 
        deriving (Eq, Ord, Show, Read)

This is an example of the text file.

[Film "Blade Runner" "Ridley Scott" 1982 [("Amy",5), ("Bill",8), ("Ian",7), ("Kevin",9), ("Emma",4), ("Sam",7), ("Megan",4)],
 Film "The Fly" "David Cronenberg" 1986 [("Megan",4), ("Fred",7), ("Chris",5), ("Ian",0), ("Amy",6)]]

This is the option 2 function.

allFilms :: [Film] -> String
allFilms [] = []
allFilms ((Film title director year ratings):films) = "\n Title: " ++ title ++ "\n Director: " ++ director ++ "\n Year: " ++ show year ++ "\n Rating: " ++ printf "%3.2f" (averageRating ratings) ++ "\n" ++ allFilms films

This is the UI code have so far:

main :: IO ()
main = do 
contents <- readFile "films.txt"
let database = (read contents :: [Film])
putStrLn "-----------------------------"
putStrLn "Welcome to the Movie Database"
putStrLn "-----------------------------"
putStrLn"Please Enter Your Name: "
user <- getLine
putStrLn user
menu database user

menu :: [Film] -> String -> IO()
menu database user = do
putStrLn "This is the Main Menu"
putStrLn "Choose one of the following options:"
putStrLn "2. give all films in the database"
putStrLn "Your Option:"
functionSelected <- getLine
if (read functionSelected :: Int) > 0 && (read functionSelected :: Int) < 9 then do
    putStrLn ("You chose option: " ++ functionSelected)
    completeFunction functionSelected database user
else do
    putStrLn "Incorrect option restarting menu."


completeFunction :: String -> [Film] -> String -> IO()
completeFunction "2" database user = do
putStrLn "Option 2: "
putStrLn (allFilms database) 

I am aware the incorrect option restarting menu does not work yet.

Cœur
  • 37,241
  • 25
  • 195
  • 267
AndyGos
  • 1
  • 1
  • The derived `Read` instance almost never do what you want it to do, you have to write a proper parser instead of `let database = (read contents :: [Film])` – zakyggaps Mar 10 '16 at 13:55
  • I just cut and pasted your file identically, including the sample data, and it works for me. There is nothing wrong with the `Read` instance. I suspect that the data file you have is in the wrong format, perhaps? Can you run `xxd films.txt` and show us what you have? – jamshidh Mar 10 '16 at 16:46
  • There's only one guarantee on `read`: you can `read` what has been `show`ed. – Zeta Mar 11 '16 at 09:49
  • jamshidh was correct my full films.txt was incorrect thank you for the help – AndyGos Mar 11 '16 at 14:57

0 Answers0