Kevin Meredith
Kevin Meredith

Reputation: 41939

Getting Result of IO Monad in ghci

Given:

Prelude> let x = return 100 :: IO Int

Trying to evaluate x returns its wrapped value.

Prelude> x
100

But, I can't get its value via show.

Prelude> show x

<interactive>:4:1:
    No instance for (Show (IO Int)) arising from a use of ‘show’
    In the expression: show x
    In an equation for ‘it’: it = show x

What's going on when I type x in ghci?

Upvotes: 3

Views: 664

Answers (2)

chi
chi

Reputation: 116174

You can't show an IO Int action. The action may require to perform side effects to produce the Int, such as asking the user for such number. Instead, the type of show promises to return a String, i.e. a plain, pure string without any side effect.

You can define your own effectful variant of show, if you want:

showIO :: Show a => IO a -> IO String
showIO = fmap show 

Note how the result above is not a plain string, but is wrapped inside the IO monad, as it should be.

Upvotes: 4

sepp2k
sepp2k

Reputation: 370455

If you enter an expression of type IO t into GHCi, it unwraps it and prints the resulting value. That is if you enter ioExp, GHCi executes val <- ioExp; print val (whereas if you enter a non-IO expression exp, GHCi executes print exp).

Upvotes: 8

Related Questions