Finkelson
Finkelson

Reputation: 3023

Is this a Monad implementation?

I wrote a simple Scala code which is a Monad implementation, in my opinion.

Here is a base trait:

trait M[A] {

  def unit(x: A): M[A]

  def bind[B](f: A => M[B]): M[B]

}

Implementation:

case class Monad(e: String) extends M[String] {    

  def unit(x: String): M[String] = {
    Monad(x)
  }

  def bind[B](f: (String) => M[B]): M[B] = {
    f(e)
  }    

}

Could anyone confirm if it is a true Monad implementation or not?

Upvotes: 1

Views: 97

Answers (1)

Lee
Lee

Reputation: 144226

This isn't a monad since it has the wrong kind. Your monad trait should be defined for a type constructor with a single type argument e.g.

trait Monad[M[_]] {
    def unit[A](a: A): M[A]
    def bind[A, B](ma: M[A], bf: A => M[B]): M[B]
}

Note the methods unit and bind are generic in the 'value' types A and B.

then your implementations should be for a particular type constructor (e.g. Option, List), for example

implicit object ObjectMonad extends Monad[Option] {
    def unit[A](a: A) = Some(a)
    def bind[A, B](oa: Option[A], bf: A => Option[B]): Option[B] = {
        oa match {
            case Some(a) => bf(a)
            case None => None
        }
    }
}

Upvotes: 5

Related Questions