error handling - Haskell: Why do the Maybe and Either types behave differently when used as Monads? -


I'm trying to get my head to deal with an error in Haskell. I've found the article "" but I'm confused as to why and maybe behave differently.

For example:

  import control. Error myDiv:: (Monad M) => Float - & gt; Float - & gt; M float myDiv x 0 = "my divison from zero" failed myDiv x y = return (x / y) testMyDiv1 :: float - & gt; Float - & gt; String Testmedia 1x y = case myDiv x y Left E - & gt; E Write R - & gt; Show r testMyDiv2 :: float - & gt; Float - & gt; String Testimedive 2 x y = Case myDiv x y nothing - & gt; "An error" simply R -> Returns the result of   

calling testMyDiv2 1 0 "an error" , but calling testMyDiv1 1 0 code : Gives:

  "Exception: my divison from zero  

(note the lack of note closure, it shows that this is someone The short answer is that the Monad class in Haskell, the original mathematical form of Monad, is not a string.

The idea has been added to the failed operation, to which it is somewhat controversial How can it either create a type of type in Haskell Monad

  • There are several ways to do this .

    Failure = Left . It seems that most people are expected, but this can not really be strict in Haskell 98. For example example Monad (or So the string) is , which is not legal under H-998 because it contains the parameters of either a either (in GHC, flexible inter-extension From the compiler will be the reason for accepting it).

  • Ignore error by using the default code, which just calls error what's going on in your example. This version has the advantage of conforming to the H8 898, but there is a loss to the user not surprising (with the surprise of the runtime).
  • The failed implementation calls some other class to change any type of string it is done in the control of MTL. Moded. Error module, which declares example error e = & gt; Monad (E either) . In this implementation, failed msg = left (strMsg msg) . It is once again legal H9 8, and sometimes surprises users as it offers another type of class. Although unlike previous examples, time comes to surprise in compilation.

Comments