Haskell: can't use "map putStrLn"?

I have a list of strings and tried this:

ls = [ "banana", "mango", "orange" ] main = do map PutStrLn list_of_strings 

This did not work, and I do not understand why.

 ghc print-list.hs print-list.hs:3:0: Couldn't match expected type `IO t' against inferred type `[IO ()]' In the expression: main When checking the type of the function `main' 

Any clues? I believe this is due to the map display, not the value, but I have not found an easy way to fix this.

Currently, the only way I know to print a list of strings is to write a function that will iterate over the list, print each element (print if list [a], but print and recurs if it (a: b)). But it would be much easier to use a map ...

Thank!

+49
io haskell monads
May 31 '09 at 19:08
source share
2 answers

The type of the main function must be IO t (where t is a type variable). Type map putStrLn ls - [IO ()] . This is why you get this error message. You can verify this by doing the following in ghci :

 Prelude> :type map putStrLn ls map putStrLn ls :: [IO ()] 

One solution to the problem is mapM , which is the "monadic" version of map . Or you can use mapM_ , which is the same as mapM , but does not collect return values ​​from a function. Since you do not need to return putStrLn , it is more advisable to use mapM_ here. mapM_ has the following type:

 mapM_ :: Monad m => (a -> mb) -> [a] -> m () 

Here's how to use it:

 ls = [ "banana", "mango", "orange" ] main = mapM_ putStrLn ls 
+87
May 31 '09 at 19:28
source share

Ayman's answer makes sense for this situation. In general, if you have [m ()] and you want m () , use sequence_ , where m can be any monad, including IO .

+19
May 31 '09 at 19:32
source share



All Articles