Why does the fail method have to exist in a class like monad?

So, I have this line of code:

[Nothing] >>= \(Just x) -> [x]

which, of course, gives an exception because the template does not match Nothing.

On the other hand, this code gives a different result, []:

do
  Just x <- [Nothing]
  return x

As I can see, they should give the same result, because do-blocks should be removed in use (→ =) and returned. But this is not the case that makes do-notation a function, not syntactic sugar.

I know that an error exists in a class like monad, and I know that it is called when a pattern match fails in the do block, but I cannot understand why this is wanted behavior, which should be different from the usual monad.

So my questions are: why should there be a failure method?

+4
source share
1

,

\(Just x) -> ...

. : . (, is Nothing), , / .

, do -, : monad. , . , Haskell fail .

, . , Monad fail, ,

do ... 
   Just x <- ...
   ...

MonadFail Monad. , , .

catMaybes xs = do Just x <- xs
                  return x
-- or
catMaybes xs = [ x | Just x <- xs ]

Nothing .

+1

All Articles