
Hi, Please can anyone point out the correct way of doing this - I am simply trying to print "Test" in a loop based on the counter derived from the list - ---- do _ <- [1..4] b <- putStrLn "Test" return b --- The intended output is to print 'Test' 4 times. Clearly there is a mismatch between the Monad types but I can't see how to achieve this without causing the conflict. Thanks, Shishir

Hello, First of all, putStrLn has type IO (), so b is pretty useless in your code, it's going to have type (), and the only value of this type is (). The simplest way to perform some action based on a list and discard the results is mapM_: mapM_ (\_ -> putStrLn "Test") [1..4] though if you discard the list's elements too, you can use sequence_ and replicate instead: sequence_ . replicate 4 $ putStrLn "Test" As a side note, if you actually want to combine monads (like list and IO) you can use monad transformers. The ListT type from transformers library has some issues as far as I know, but you can use the one from pipes, for example. Have a look at: http://www.haskellforall.com/2014/11/how-to-build-library-agnostic-streaming... Best regards, Marcin Mrotek

putStrLn "Test" is a IO value, that prints the string "Test". To sequence such monadic values, we use sequence or sequence_ (which ignores the results). "sequence [a, b, c, d]" is equivalent to "a >> b >> c >> d" "sequence_ [a, b, c, d]" is equivalent to "a >> b >> c >> d >> return ()" There are similar functions mapM and mapM_, which can be used as follows. mapM f [a, b, c] == sequence (map f [a,b,c]) == sequence [f a, f b, f c] == f a >> f b >> f c and, mapM_ f [a, b, c] == f a >> f b >> f c >> return ()
From mapM_, we can create a convenience function forM_
forM_ = flip mapM_
All the above are exported by Control.Monad
On 1 May 2015 at 18:10, Shishir Srivastava
Hi,
Please can anyone point out the correct way of doing this - I am simply trying to print "Test" in a loop based on the counter derived from the list -
---- do _ <- [1..4] b <- putStrLn "Test" return b ---
The intended output is to print 'Test' 4 times.
Clearly there is a mismatch between the Monad types but I can't see how to achieve this without causing the conflict.
Thanks, Shishir
_______________________________________________ Beginners mailing list Beginners@haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
-- Regards Sumit Sahrawat
participants (3)
-
Marcin Mrotek
-
Shishir Srivastava
-
Sumit Sahrawat, Maths & Computing, IIT (BHU)