When are [do x] and [do return x] evaluated differently?

*Main> do 0 

0

 *Main> do return 0 

0

 *Main> do (Just 0) 

Just 0

 *Main> do return (Just 0) 

Just 0

 *Main> do Nothing 

Nothing

 *Main> do return Nothing 

Nothing

 bareDo :: a -> a bareDo x = do x doReturn :: Monad m => a -> ma doReturn x = do return x 

Why do x and do return x evaluate the same thing, and when they will not?

I am trying to understand Monad , there was enough tutorial and discussion , but I could not understand.

It is even a post

Do not read monad textbooks.

So, I guess my hand might be dirty.

I really appreciate whoever helps me out of here (I mean do and return , not Monad ). I know it will take several days).

+5
source share
2 answers

do in one expression does nothing: itโ€™s just a syntactic herald indicating that you can use a sequence of actions (which requires a monad), but if you donโ€™t do this, it has the same effect as wrapping an expression in layers of redundant parentheses.

So your sample session is equivalent to this:

 Prelude> 0 0 Prelude> return 0 0 Prelude> Just 0 Just 0 Prelude> return (Just 0) Just 0 Prelude> Nothing Nothing Prelude> return Nothing Nothing 

Now the question is why return does nothing. Well, actually it is, you just do not see it, because GHCi hides implementation details. GHCi has two fundamentally different ways of interactive evaluation:

  • Actions in progress
  • IO , then the result is print ed.
  • Everything else print ed, as it is.

Unfortunately, GHCi is quite difficult to interpret everything as an IO action before continuing with 2. Therefore, if you give it an ambiguous expression like return 0 , it notices that one possible instance is IO Integer . He immediately sets this by default by default, performs this free action on the side effect, and everything that you see as a result is thus 0 . This happens only for IO , but not for other monads:

 Prelude> return 0 :: IO Integer 0 Prelude> return 0 :: Maybe Integer Just 0 Prelude> return 0 :: [] Integer [0] 

GHCi simply has a default value of IO when the monad is ambiguous, but in Haskell this will not happen otherwise.

+19
source

Good answer: never, since return :: Monad m => a -> ma takes an object and puts it in a field.

Correct, but not applicable answer: when x is a fixed point from return from the given monad.

-1
source

All Articles