Reputation: 321
I have this which works fine:
forM_ [1..10] $ \x -> myFunc1 x 99 >>= putStrLn . show >> return ()
myFunc1 :: Int -> Int -> IO Bool
myFunc1 .....
I want to do add an additional string to the output:
forM_ [1..10] $ \x -> myFunc1 x 99 >>= (++) "the result is: " >>= putStrLn . show >> return ()
But that doesn't compile. I've tried different variations but still no success. Your suggestions?
Upvotes: 0
Views: 87
Reputation: 14825
Replace ++
with add
add x y = return (x ++ show (y))
forM_ [1..10] $ \x -> myFunc1 x 99 >>= add "the result is: " >>= putStrLn . show >> return ()
reason: The return type of ++
is not IO
type
Upvotes: 0
Reputation: 52029
The first thing that sticks out is that the expression:
(++) "the result is: "
is not an IO-action - it's just a pure function String -> String, and that's one reason why you code isn't type checking.
To turn it into an IO-action you can compose it with return
:
return . ( (++) "the result is: " )
:: String -> IO String
Now you can use it with >>=
.
However, that's not where the real problem is...
To prepend "the result is: " before the show
you have to insert it in the putStrLn
call:
... >>= putStrLn . (++ "the result is: ") . show
(Note that there is no need to >> return ()
since putStrLn
already returns ()).
Honestly, this is a lot simpler using do-notation:
forM_ [1..10] $ \x -> do
s <- myFunc1 x 99
putStrLn $ "the result is: " ++ show s
Upvotes: 7
Reputation: 461
You can compose show
with the concatenation function like so:
forM_ [1..10] $ \x -> myFunc1 x 99 >>= putStrLn . ("the result is: " ++) . show >> return ()
Upvotes: 1