mrq*_*ion 2 io monads haskell types
你能告诉我为什么我有错误'无法将预期类型IO t与推断类型字符串匹配' - 请参阅下面的内容以查看错误行:
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";
Run Code Online (Sandbox Code Playgroud)
showingRectangles是一个返回字符串的纯函数.为什么do在这里使用表示法?将其更改为printRectangle x ++ showingRectangles xs.
由于showRectangles它只是一个纯函数,它不会打印到控制台.因此"声明" showRectangles rs无效.你需要putStrLn它.
"3" -> do { putStrLn (showRectangles rs); menuRectangles rs }
Run Code Online (Sandbox Code Playgroud)(顺便说一句,通过这个简单的修复,showingRectangles它将始终显示Empty在最后一行.您需要在函数中添加一个更多的定义以避免这种情况.)