5

I was wondering if scala Either is really a Monad in Category Theory sense?. I know that Monads should have bind and return methods. What is Either's bind then?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
goral
  • 1,275
  • 11
  • 17
  • http://scabl.blogspot.com/2013/02/monads-in-scala-1.html: *The binding operation, as a Scala function, would have the following signature:* `def bind[A, B](Maybe[A])(A => Maybe[B]): Maybe[B]` – Robert Harvey Nov 24 '14 at 09:05
  • I would argue that Haskell `Maybe` in Scala is more like an `Option` than `Either`. `Either` is cooproduct of types. – goral Nov 24 '14 at 09:08
  • Read the article. It addresses that. – Robert Harvey Nov 24 '14 at 09:09

1 Answers1

5

Yes, it really is - otherwise it would be in scalaz-outlaws. Either's bind is defined something like:

trait Either[A, B] {
  def bind[C](f: B => Either[A, C]) = this match {
    case Right(b) => f(b)
    case Left(a) => Left(a)
  }
}

(in practice it's defined via a typeclass, but the above definition would work)

I guess it's more proper to say that for a fixed A, the type ({type L[B]=Either[A, B]})#L forms a Monad, so Either is more a class of Monads than a Monad in its own right, but that's an exceedingly technical distinction.

But it really is a Monad; it satisfies all the monad laws.

lmm
  • 17,386
  • 3
  • 26
  • 37
  • So it is more precise to say that `Right` and `Left` are `Monads` whereas `Either` itself is not, but its subclasses? – goral Nov 24 '14 at 10:45
  • 1
    No, that's wrong. `Left` on its own is not a `Monad` at all, and `Right` on its own is just the identity `Monad`. If you want to be precise a `Monad` is not really a trait (which after all is not a mathematical concept) so much as a set and a pair of operations. So it's more like "for any `A`, the set of all `Either[A, B]` forms a monad under the operations `bind=...` and `point=...`). – lmm Nov 24 '14 at 10:56
  • As of Scala 2.12, Either became right biased. So technically, Either at the root became more uniform with the other Monad implementations (in that one didn't have to select a projection from which to then further Monad operations). – chaotic3quilibrium May 26 '17 at 14:33
  • @Imm @goral One could define an instance of `Monad` just for `Left` (although it would probably look a whole lot like the instance of `Monad` for `Id` in `scalaz`) so it's not incorrect to say that Left "is" a `Monad`. But certainly, an instance of `Monad` can be defined for `Either` (which is usually what's done), so saying that `Either` is not a `Monad` is incorrect. – jedesah Jun 24 '17 at 23:45