Try a monad if unit = Success?

With unit = Try , Try not a monad, because the law of the left block fails.

  Try(expr) flatMap f != f(expr) 

But what is the question: is this Try monad if unit = Success ?

In this case:

  Success(expr) flatMap f == f(expr) 

So this is the monad.

Do I understand correctly?

+5
source share
2 answers

Get an answer from Alexey's help on the coursera forum:

When unit = Success , for the left unit law:

 Success(throw new Exception) flatMap f == f(throw new Exception) // holds Success(s) flatMap (x => throw new Exception) == Failure(new Exception) // does not hold 

It actually loses again, unless of course you override flatMap to throw exceptions again, while losing the main Try functions

+2
source

Essentially, yes. Monads are usually defined in a purely functional language, where equality == has the usual properties of equality, i.e. We can replace equals for equals. If you are in such a subset of Scala, then you can really give a natural definition of a parametric type, representing perhaps an exceptional calculation. Here is an example. The example does occur with mechanical verification in the Leon verification system for Scala ( http://leon.epfl.ch ).

 import leon.lang._ object TryMonad { // Exception monad similar to Option monad, with an error message id for None sealed abstract class M[T] { def bind[S](f: T => M[S]): M[S] = { this match { case Exc(str) => Exc[S](str) case Success(t) => f(t) } } } case class Exc[T](err: BigInt) extends M[T] case class Success[T](t: T) extends M[T] // unit is success def unit[T](t:T) = Success(t) // all laws hold def leftIdentity[T,S](t: T, f: T => M[S]): Boolean = { unit(t).bind(f) == f(t) }.holds def rightIdentity[T](m: M[T]): Boolean = { m.bind(unit(_)) == m }.holds def associativity[T,S,R](m: M[T], f: T => M[S], g: S => M[R]): Boolean = { m.bind(f).bind(g) == m.bind((t:T) => f(t).bind(g)) }.holds } 
+3
source

All Articles