Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Scalas Either not a monad?

Tags:

scala

I'm interested in knowing the design decisions why scala.Either was not done as a monad. There already exists some discussion on how to right-biasing Either, for example:

  • right-biasing Either
  • fixing Either
  • Fixing scala.Either - unbiased vs biased

But there are mentioned too much details and I couldn't get an complete overview about why it is done as it is done. Can someone give an overview about the benefits of having a right-biased Either, about the problems to do it that way and about the benefits of not having an right-biased Either (if they even exist)?

like image 340
kiritsuku Avatar asked Sep 05 '12 22:09

kiritsuku


People also ask

Does Scala have monads?

Monad in scala are a category of data types. Informally, anything that has a type parameter, a constructor that takes an element of that type, and a flatMap method (which has to obey certain laws) is a monad. A monad is a mechanism for sequencing computations.

What is either in Scala?

In Scala Either, functions exactly similar to an Option. The only dissimilarity is that with Either it is practicable to return a string which can explicate the instructions about the error that appeared.


1 Answers

I think it just comes down to the Principle of Least Astonishment. Using Either to encode success or failure is clearly something people do, but it is not the only use of Either. In fact, there is not much reason to have Right be success and Left be failure other than tradition. As adelbertc's comment above mentions, scalaz has Validation which specifically encode this.

To further justify the POLA claim above, take this code:

def foo(): Either[Int, Int] = Right(1)
def bar(j: Int): Either[Int, Int] = Left(1)
def baz(z: Int): Either[Int, Int] = Right(3)

// Result is Left(1) 
for (a <- foo().right; b <- bar(a).right; c <- baz(b).right) yield c

This compiles because I am using the .right projection in the for expression. It makes sense here the Left(1) in bar is the failure case and so that is the result, but imagine if Either was Right-biased. The above code would compile without the .right projections in the expression like:

for (a <- foo(); b <- bar(a); c <- baz(b)) yield c

If you used Either in your code to just be a "one-or-the-other" type, you would be surprised by (1) the fact that this would compile and (2) that it returns Left(1) and seemingly never executes baz.

In summary, use Validation if you want to use Either to encode success or failure.

like image 131
3 revs Avatar answered Oct 19 '22 13:10

3 revs