The definition of (>>)
function is following:
(>>) :: Monad m => m a -> m b -> m b
But I would like to achieve this function flipped like following:
I have a function tabulate :: Int -> [Int] -> IO Int
which prints the list as a table with the given number of columns and returns a sum of all the list items in the IO
monad.
After that I want to have an explicit putStr "\n"
.
If I would use following:
tabulate >> (putStr "\n")
it would discard the result of the tabulate, the other way around it would not print newline after the table.
In case of doing this in do
:
smth = do
let a = tabulate
putStr "\n"
a
This do would again print newline before the table since the a
is evaluated after the putStr
.
How would you print newline after the tabulate function?
CodePudding user response:
You can work with (<*) :: Applicative f => f a -> f b -> f a
here:
smth :: IO Int
smth = tabulate 14 [2, 5] <* putStr "\n"
This is equivalent to:
smth = do
a <- tabulate 14 [2, 5]
putStr "\n"
return a
It thus first evaluates the IO Int
of the tabulate 14 [2, 5]
, then prints "\n"
as actions, but it "returns" the value of the tabulate
call, and not that of the putStr
call.