fmap print value doesn't print anything

2019-08-02 19:20发布

Why does the following doesn't print anything:

λ> fmap print (pure 2)

Whereas something like this works:

λ> fmap id (pure 2)
2

2条回答
相关推荐>>
2楼-- · 2019-08-02 20:16

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
查看更多
狗以群分
3楼-- · 2019-08-02 20:25

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 some a, 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.

查看更多
登录 后发表回答