Why does the following doesn't print anything:
λ> fmap print (pure 2)
Whereas something like this works:
λ> fmap id (pure 2)
2
Why does the following doesn't print anything:
λ> fmap print (pure 2)
Whereas something like this works:
λ> fmap id (pure 2)
2
Follow the types:
fmap print (pure 2) :: Applicative f => f (IO ())
fmap id (pure 2) :: (Num b, Applicative f) => f b
Lets replace f
with IO
:
fmap print (pure 2) :: IO (IO ()) -- #1
fmap id (pure 2) :: (Num b) => IO b -- #2
Now you can clearly see that #2 is an action with a numeric result, whereas #1 is an action with another action as a result.
Also, GHCi has the following rules about interactive evaluation:
2.4. Interactive evaluation at the prompt
When you type an expression at the prompt, GHCi immediately evaluates and prints the result:
2.4.1. I/O actions at the prompt
GHCi does more than simple expression evaluation at the prompt. If you type something of type
IO a
for somea
, then GHCi executes it as an IO-computation.Furthermore, GHCi will print the result of the I/O action if (and only if):
The result type is an instance of
Show
.The result type is not ().
Since IO a
is not an instance of Show
, it won't print the result of the IO action.
Your expression return a computation (no perform it).
You want
fmap print (pure 2) >>= id
with that, we get your computation and run it inside monad.
Look your types
fmap print (pure 2) :: Applicative f => f (IO ())
Note
fmap print (pure 2) >>= id -- #1
is very different (but same "visual" result) than
fmap id (pure 2) -- #2
with #1 we take a computation and run it inside monad printing a number
with #2 we take a number and get value through fmap
returning a number
(looking types again
fmap id (pure 2) :: (Num b, Applicative f) => f b