Haskell IO代码无法通过类型检查

3

我是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 }

您可以使用Functors(参见:http://learnyouahaskell.com/functors-applicative-functors-and-monoids)来消除“getLines”函数。您可以这样写:“ls <- fmap lines $ readFile file”。 - Daniel
1个回答

9

map parsePerson lines 的类型是 [Person],但由于你需要的 loadPeople 的结果类型是 IO [Person],所以你需要使用 return 将其包装为 IO

return $ map parsePerson lines

是的!谢谢。现在我想起来了,这完全有道理。 - Alex Baranosky
严重的迟到评论:最好将其编写为liftM(parsePerson lines)$ getLines file。请记住,每当您有一个两行的单调函数时,通常有更好的编写方式。 - alternative

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接