无法匹配 haskell 中的预期类型错误

1 haskell functional-programming

我\xc2\xb4m试图实现一个通过txt文件保存游戏中玩家最高分的功能。这是代码:

\n
import System.IO\nimport System.Directory\n\nsaveHighScore:: Int -> IO()\nsaveHighScore num = do\n  let stringNum = "" ++ show num\n  let file = "score.txt"\n  writeFile file stringNum\n\nreadHighScore:: IO() -> Int\nreadHighScore = do \n  content <- openFile "score.txt" ReadMode\n  score <- hGetContents content\n  let highScore = read score :: Int\n  return highScore\n
Run Code Online (Sandbox Code Playgroud)\n

但代码给出了这个错误,我不知道该怎么做:

\n
localStorage.hs:17:9: error:\n* Couldn't match expected type: IO () -> Int\n              with actual type: IO Int\n* In a stmt of a 'do' block:\n    content <- openFile "score.txt" ReadMode\n  In the expression:\n    do content <- openFile "score.txt" ReadMode\n       score <- hGetContents content\n       let highScore = ...\n       return highScore\n  In an equation for `readHighScore':\n      readHighScore\n        = do content <- openFile "score.txt" ReadMode\n             score <- hGetContents content\n             let highScore = ...\n             ....\n |\n17|         content <- openFile "score.txt" ReadMode\n |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n
Run Code Online (Sandbox Code Playgroud)\n

ama*_*loy 5

错误消息准确地告诉您出了什么问题。您声称您的函数具有 type IO () -> Int,但任何有趣的函数都不可能具有这种类型。唯一可能的实现是一个常量函数,它忽略IO ()并产生相同的结果,无论其输入如何。

正确的类型是编译器建议的类型,IO Int.