I need some help with types in Haskell…
Here’s the code I’m working on:
loadManyPeople :: [FilePath] → IO [Person]
loadManyPeople fs = do
return $ concat $ map loadPeople fs
loadPeople :: FilePath → IO [Person]
loadPeople file = do
lines ← getLines file
return $ map parsePerson lines
loadPeople is fine. I want loadManyPeople to load all the Persons from each file, then concat them into one list of Persons.
I’m new to Haskell and need help with getting the types to work out.
Thanks for the help.
Alex
loadPeoplegives you anIO [Person], somap loadPeoplegives you a[IO [Person]], however to useconcat, you’d need a[[Person]].To fix this, you can use sequence, which is a function of type
[IO a] -> IO [a], so you can do the following:However there’s a shortcut for using
mapand thensequence:mapMwhich has type(a -> IO b) -> [a] -> IO [b]. WithmapMyour code looks like this:This can be written more succinctly using Applicative: