2016-10-07

Monad implementation in Scala with example

Monad in Scala

Monad

Difficult to explain but useful for nice code.

Implementation in Scala

This is a simple implementation of a monad in Scala which makes Any able to use monad's definition called flatmap (>>=).
/**
 * Monad implementation
 */
final case class Monad[T](val value : T) {

  def >>=[S](f : T => S) : Monad[S] = {
    new Monad(f(value))
  }

  override def toString = String.valueOf(value)
}

/**
 * Implicit wrap Any to a Monad.
 */
implicit def anyToMonad[T](value : T): Monad[T] = new Monad[T](value)

Example

Using this implementation, Any can use flatmap wihch could be used as follows.
// Example
"10" >>= Integer.parseInt >>= (_ + 10) >>= (0 to _) >>= println
Prints
Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

Fiddle

Try it out at Scala Fiddle!

Inga kommentarer:

Skicka en kommentar