I’m just totally confused with lists and monads, so maybe my question isn’t correct or very naive.
I’ve seen the way to do it using mapM_ func here:
mapM_ print [1, 2, 3, 4]
But I don’t know exactly how it works and want to know how can I do this in a way like this:
x <- [1, 2, 3]
print x
or, if I understood it right:
[1, 2, 3] >>= print
I understand that [1, 2, 3] has type [a] and print has type Show a => a -> IO (). Also I understand that for using monad List we need type List a on the left and func with type a -> List b on the right. Am I right?
Can you help me with this?
UPD. Thanks @MathematicalOrchid for explanation how mapM_ works. From my side I want to explain that the real problem is not printing any results in different lines but do some monadic actions(because now I’m hanging around OpenGL stuff) in a way monad List provides it. But I got that the root of misunderstanding was in mixing monads.
UPD2. Thanks everyone for answers. I apologize for this kinda fuzzy question. I dind’t exactly know what answer I need and what is the question. It’s because I didn’t understand some basics. So it’s hard to choose “the correct answer” now because every answers have a small peace of what I was looking for. I’ve decided to choose the closest(although not the most useful now) to what I wanted.
What you want cannot work this way since you are trying to mix two monads together:
Specifically you are mixing the
IOand the[]monads. In do-notation, all the statements should have the typem afor some Monadm. But in the above code, the first statement has the type[Integer]while the second statement has the typeIO ().To get the effect you want you should use the
ListTmonad transformer. Monad transformers allow mixing monads together in a certain order in a stack and combining their effects as needed.This will return a value of type
ListT IO Integer. To get theIOcomputation out of this transformer, userunListT. Which will return a value of typeIO [Integer]. This will output:Which is equivalent to
mapM print [1,2,3]. To throw away the list and get the effect ofmapM_ print [1,2,3]you can usevoidfromControl.Monad.