Make an arbitrary class in Scala as a monad instance
monads, scala
Solution
Take a look at `scalaz`:
// You could use implementation in the end of this answer instead of this import
import scalaz._, Scalaz._
sealed trait Z[T]
case class MyZLeft[T](t: T) extends Z[T]
case class MyZRight[T](t: T) extends Z[T]
def swap[T](z: Z[T]) = z match {
case MyZLeft(t) => MyZRight(t)
case MyZRight(t) => MyZLeft(t)
}
implicit object ZIsMonad extends Monad[Z] {
def point[A](a: => A): Z[A] = MyZRight(a)
def bind[A, B](fa: Z[A])(f: A => Z[B]): Z[B] = fa match {
case MyZLeft(t) => swap(f(t))
case MyZRight(t) => swap(f(t))
}
}
Usage:
val z = 1.point[Z]
// Z[Int] = MyZRight(1)
z map { _ + 2 }
// Z[Int] = MyZLeft(3)
z >>= { i => MyZLeft(i + "abc") }
// Z[String] = MyZRight(1abc)
z >>= { i => (i + "abc").point[Z] }
// Z[String] = MyZLeft(1abc)
`for-comprehensions` (similar to do-notation):
for {
i <- z
j <- (i + 1).point[Z]
k = i + j
} yield i * j * k
// Z[Int] = MyZRight(6)
See also Scalaz cheatsheet and Learning scalaz.
There is no magic in `scalaz` - you could implement this without `scalaz`.
Related: Typeclases in Scala & Haskell.
Simplest implementation of `Monad` with syntax in case you don't want to use `scalaz`:
import scala.language.higherKinds
trait Monad[M[_]] {
def point[A](a: => A): M[A]
def bind[A, B](fa: M[A])(f: A => M[B]): M[B]
}
implicit class MonadPointer[A](a: A) {
def point[M[_]: Monad] = implicitly[Monad[M]].point(a)
}
implicit class MonadWrapper[M[_]: Monad, A](t: M[A]) {
private def m = implicitly[Monad[M]]
def flatMap[B](f: A => M[B]): M[B] = m.bind(t)(f)
def >>=[B](f: A => M[B]): M[B] = flatMap(f)
def map[B](f: A => B): M[B] = m.bind(t)(a => m.point(f(a)))
def flatten[B](implicit f: A => M[B]) = m.bind(t)(f)
}
Problem
In order to make anything operable in monad context, if using Haskell - I just add implementation of class Monad for given type anywhere. So I don't touch a source of the data type definition at all. Like (something artificial) ``` data Z a = MyZLeft a | MyZRight a swap (MyZLeft x) = MyZRight x swap (MyZRight x) = MyZLeft x instance Monad Z where return a = MyZRight a (>>=) x f = case x of MyZLeft s -> swap (f s) MyZRight s -> swap (f s) ``` so I'm not touching definition of Z, but make it as a monad How do I do this in Scala? It seems that there's no way besides of mixing some traits in and defining methods map/flatMap/filter/withFilter ?