【问题标题】:Haskell IO code doesn't typecheckHaskell IO 代码不进行类型检查
【发布时间】:2023-04-03 18:43:01
【问题描述】:

我是 Haskell 的初学者,在搞清楚一些代码时遇到了麻烦。我需要做什么才能在我的代码的这个 IO 部分中正确设置类型?

提前致谢。

loadPeople :: FilePath -> IO [Person]
loadPeople file = do
   lines <- getLines file
   map parsePerson lines

getLines :: FilePath -> IO [String]
getLines = liftM lines . readFile

parsePerson :: String -> Person
parsePerson line = ...........

map 在 Leksah 中带有红色下划线,我收到的编译错误是:

src\Main.hs:13:3:
    Couldn't match expected type `IO [Person]'
           against inferred type `[Person]'
    In the expression: map parsePerson lines
    In the expression:
        do { lines <- getLines file;
             map parsePerson lines }
    In the definition of `loadPeople':
        loadPeople file
                     = do { lines <- getLines file;
                            map parsePerson lines }

【问题讨论】:

标签: haskell io monads typechecking


【解决方案1】:

map parsePerson lines 的类型为[Person],但由于您需要loadPeople 的结果类型为IO [Person],因此您需要使用IO 将其包装在IO 中:

return $ map parsePerson lines

【讨论】:

  • 是的!谢谢。这完全有道理,现在我想起来了。
  • 严重迟到的评论:最好写成liftM (parsePerson lines) $ getLines file。请记住,只要你有一个两行一元函数,通常都有更好的方法来编写它。
猜你喜欢
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多