I've been trying to print 2 values separately, and I tried this code:
import System.Directory
main = getCurrentDirectory >>= \x -> (print <$> doesFileExist x) >> (print <$> doesDirectoryExist x)
but it doesn't print anything however the following code works fine:
import System.Directory
main = getCurrentDirectory >>= \x -> doesFileExist x >>= print >> doesDirectoryExist x >>= print
any reasons for why the 1st code doesn't print anything ?
If you fmap print over an IO action, you don't get an IO action that performs this printing. You just get an IO action that performs whatever side-effects the original action had, but instead of yielding the printable value as the result it yields another IO action as the result which you could then execute in a separate step:
import Control.Applicative
import Data.Time
printCurrentTime :: IO ()
printCurrentTime = do
tPrinter <- print <$> getCurrentTime
tPrinter
or, without do notation,
printCurrentTime = print <$> getCurrentTime >>= \tPrinter -> tPrinter
In other words,
printCurrentTime = print <$> getCurrentTime >>= id
By the monad laws, f <$> a >>= b is the same as a >>= b . f, i.e.
printCurrentTime = getCurrentTime >>= id . print
which is the same as simply
printCurrentTime = getCurrentTime >>= print
That could than be written with do notation as
printCurrentTime = do
t <- getCurrentTime
print t
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With