3

I'm a beginner with Haskell and am having trouble figuring out some code. What do I need to do to get the types right on this IO section of my code?

Thanks in advance.

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 is underlined in red in Leksah, and the compile error I am receiving is:

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 }
1

1 Answer 1

9

map parsePerson lines has type [Person], but since you need the result type of loadPeople is IO [Person], you need to wrap it in IO using return:

return $ map parsePerson lines
Sign up to request clarification or add additional context in comments.

2 Comments

YES! Thanks. That makes total sense, now that I think of it.
Seriously late comment: Better to write this as liftM (parsePerson lines) $ getLines file. Keep it mind that whenever you have a two line monadic function theres usually a better way to write it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.