【发布时间】:2011-04-22 11:59:53
【问题描述】:
我的清单上可以有很多数字。每个 Figure 的列表中可以有许多 Rectangles。我的函数 checkNewRectangleId 有问题——这个函数应该询问用户新的矩形 id,直到他写出真正的新 id,然后它应该返回这个 id——但我有一个错误:无法匹配预期类型 IO t 与推断类型可能我的函数中的 figureType 行 (Figure id width height rectangles) <- findFigure idFigure x - 你能帮忙吗?
import IO
import Char
import System.Exit
import Maybe
import Data.Time.Calendar
import System.Time
checkNewRectangleId :: Int -> [FigureType] -> IO Int
checkNewRectangleId idFigure x = do
idRectangle <- getInt "Give me new rectangle id: "
(Figure id width height rectangles) <- findFigure idFigure x
if isJust (findRectangle idRectangle rectangles) then do
putStrLn ("We have yet rectangle with id " ++ show idRectangle)
checkNewRectangleId idFigure x
else return idRectangle
data FigureType = Figure Int Int Int [RectangleType] deriving(Show, Read)
data RectangleType = Rectangle Int CalendarTime deriving(Show, Read)
findFigure :: Int -> [FigureType] -> Maybe FigureType
findFigure _ [] = Nothing
findFigure n ((Figure id width height rectangles) : xs) =
if n == id then Just (Figure id width height rectangles)
else findFigure n xs
findRectangle :: Int -> [RectangleType] -> Maybe RectangleType
findRectangle _ [] = Nothing
findRectangle n ((Rectangle id date) : xs) =
if n == id then Just (Rectangle id date)
else findRectangle n xs
isInt i = not (null i) && all isDigit i
getInt :: String -> IO Int
getInt q = do
putStr q;
i <- getLine
if isInt i == False then do
putStrLn "Bad number"
getInt q
else return (read i)
【问题讨论】:
标签: haskell monads type-mismatch