Haskell: can't use “map putStrLn”?

后端 未结 2 1063
慢半拍i
慢半拍i 2020-12-23 16:05

I have a list of strings, and tried this:

ls = [ \"banana\", \"mango\", \"orange\" ]

main = do
       map PutStrLn list_of_strings

That di

2条回答
  •  渐次进展
    2020-12-23 16:53

    The type of the main function should be IO t (where t is a type variable). The type of map putStrLn ls is [IO ()]. This why you are getting this error message. You can verify this yourself by running the following in ghci:

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

    One solution to the problem is using mapM, which is the "monadic" version of map. Or you can use mapM_ which is the same as mapM but does not collect the returned values from the function. Since you don't care about the return value of putStrLn, it's more appropriate to use mapM_ here. mapM_ has the following type:

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

    Here is how to use it:

    ls = [ "banana", "mango", "orange" ]
    main = mapM_ putStrLn ls
    

提交回复
热议问题