Violation of the law of the left personality for future monads in scalas

Suppose I define an instance of the Monad class for Future :

 val futureMonad = new Monad[Future] { override def point[A](a: β‡’ A): Future[A] = Future(a) override def bind[A, B](fa: Future[A])(f: A => Future[B]): Future[B] = fa flatMap f } 

Strictly speaking, this is not a monad, since it violates the law of left identity:

 futureMonad.point(a) bind f == f(a) 

If f throws an exception, the result of the expression on the left side will be unsuccessful Future , while the right side, of course, will throw an exception.

But what are the practical consequences of this violation? How can a system fail as a result of this "misbehavior"?

+7
scala monads typeclass
source share
2 answers

It simply means, in terms of understanding, that the following refactoring does not preserve semantics:

 for (fut <- Future(a); x <- f(fut)) yield x ==> f(a) 

But this is just another way of writing the left law of identity.

To explain what invalid refactoring is next:

 for (fut <- Future(a); x <- f(fut)) yield x ==> for (x <- f(a)) yield x // by left identity law: WRONG, because left identity law does not hold ==> f(a) // by 1st functor law: WRONG, because previous line was wrong 
+4
source share

Monads, such as Try and Future , trade one monad law for another law, which is more useful in the context that they should use: An expression consisting of ( Try or Future ), a flatMap card, will never throw an exception that is not related to fatation. Call it the β€œbulletproof” principle. Thus, in fact, this approach really protects you from many failures, and the law of the left block is not intentional.

+6
source share

All Articles