Jonathan Prieto-Cubides
Jonathan Prieto-Cubides

Reputation: 2847

Using in IO monad, a function from other monad

If I have a function like, in a monad T, f1 :: T String, and I want to use its outcome, print it, for example.

seeF1 :: IO String
seeF1 = do
  res <- f1
  print res

Why is it wrong?. It seems that I can't use f1 because it is not in the monad IO. So, How can I do it? lifting?

Upvotes: 0

Views: 94

Answers (1)

Guerric Chupin
Guerric Chupin

Reputation: 461

In do notation, when you do

x = do
  y <- z
  ....

Then if x :: (Monad m) => m a, then z :: (Monad m) => m b were m is the same monad.

That is pretty logical after all : imagine if your T monad was list, what should your seeF1 return? Or if your T monad was Maybe, seeF1 wouldn't be able to print anything in case it encountered a Nothing since the result would be undefined.

Therefore in general, what you are asking for is not possible. But if you are a bit more specific about your T, then you might find a way to get an IO a from your T a. For instance if you look at the monads defined in transformers, many have a run function that transform them, and from which you can get an IO.

Upvotes: 2

Related Questions