您能否告诉我为什么会有错误“无法将预期的类型IO t与推断的类型String相匹配”-参见下文以查看错误的行:

data RectangleType = Rectangle Int Int Int deriving(Show)

menuRectangles :: [RectangleType] -> IO [RectangleType]
menuRectangles rs = do
    putStrLn "Please choose option:"
    putStrLn "3 - Show all rectangles"
    putStrLn "4 - Quit"
    putStr "Number: "
    n <- getLine
    case n of
        "3"         ->  do { showRectangles rs; menuRectangles rs }  -- this line is wrong
        "4"         ->  do { putStrLn "Quitting"; return rs }
        otherwise   ->  do { putStrLn "The End"; return rs }

showRectangles :: [RectangleType] -> String
showRectangles x = showingRectangles x

showingRectangles [] = "Empty"
showingRectangles (x:xs) = do printRectangle x
                              showingRectangles xs

printRectangle :: RectangleType -> String
printRectangle (Rectangle id width height) = "id: " ++ show id ++ "width: " ++ show width ++ "height: " ++ show height ++ "\n";

最佳答案

showingRectangles是返回字符串的纯函数。为什么在这里使用do表示法?将其更改为printRectangle x ++ showingRectangles xs
由于showRectangles只是一个纯函数,因此不会打印到控制台。因此,“声明” showRectangles rs无效。您需要putStrLn它。

"3" -> do { putStrLn (showRectangles rs); menuRectangles rs }



(顺便说一句,使用此简单的修复程序,showingRectangles将始终在最后一行显示Empty。您需要在函数中再添加一个定义以避免这种情况。)

08-27 15:31