用戶可以給id,width,height和description矩形,然後將其寫入文件。現在我想從文件加載這個內容到我的程序,但我有錯誤:Haskell程序中輸入錯誤
無法匹配預期類型[RectangleType]與推斷類型IO [Rectangletype]。 menuRectangles的第一個參數即db。在表達式menuRectangles db中。在do表達式menuRectangles db中。
這是怎麼回事?這是我的文件的內容: [矩形2 5 6 「ABCABC」,矩形1 2 4 「ABCABC」]
這是代碼:
import IO
import Char
import System.Exit
import Maybe
data RectangleType = Rectangle Int Int Int deriving(Show, Read)
loadFile :: FilePath -> IO [RectangleType]
loadFile fname =
catch (do fileContent <- readFile fname
return (read fileContent)
) errorHandler
where
errorHandler e = do putStrLn ("Error file")
exitFailure
db = loadFile "db.txt"
main = do
putStrLn "Choose option:"
n <- getLine
case n of
"1" -> do menuRectangles db; main
"2" -> putStrLn "bye, bye"
otherwise -> do putStrLn "Bad option"; main
menuRectangles :: [RectangleType] -> IO [RectangleType]
menuRectangles rs = do
putStrLn "Please choose option:"
putStrLn "1 - Add rectangle"
putStrLn "2 - Show rectangle"
putStrLn "3 - Quit"
putStr "Number: "
n <- getLine
case n of
"1" -> do { {- rs_new <- addRectangle rs; -} menuRectangles rs };
"2" -> do { {- showRectangle rs; -} menuRectangles rs }
"3" -> do { putStrLn "Quitting"; return rs }
otherwise -> do { putStrLn "The End"; return rs }
編輯: 正確的代碼:
import IO
import Char
import System.Exit
import Maybe
data RectangleType = Rectangle Int Int Int deriving(Show, Read)
loadFile :: FilePath -> IO [RectangleType]
loadFile fname =
catch (do fileContent <- readFile fname
return (read fileContent)
) errorHandler
where
errorHandler e = do putStrLn ("Error file")
exitFailure
main = do
db <- loadFile "db.txt"
mainMenu db
mainMenu rs = do
putStrLn "Choose option:"
n <- getLine
case n of
"1" -> do menuRectangles rs; mainMenu rs
"2" -> putStrLn "bye, bye"
otherwise -> do putStrLn "Bad option"; mainMenu rs
menuRectangles :: [RectangleType] -> IO [RectangleType]
menuRectangles rs = do
putStrLn "Please choose option:"
putStrLn "1 - Add rectangle"
putStrLn "2 - Show rectangle"
putStrLn "3 - Quit"
putStr "Number: "
n <- getLine
case n of
"1" -> do { {- rs_new <- addRectangle rs; -} menuRectangles rs };
"2" -> do { {- showRectangle rs; -} menuRectangles rs }
"3" -> do { putStrLn "Quitting"; return rs }
otherwise -> do { putStrLn "The End"; return rs }
爲什麼是錯誤的代碼仍然在後? – Arjan 2011-04-19 17:24:00
大概是這樣,問題和答案仍然有意義。 – 2011-04-20 16:27:24