Skip to content

Instantly share code, notes, and snippets.

@notyy
Created March 19, 2012 03:54
Show Gist options
  • Save notyy/2093930 to your computer and use it in GitHub Desktop.
Save notyy/2093930 to your computer and use it in GitHub Desktop.
monad
class Monadic[A, B](val f1: (A => Option[B])) {
def then[C]: (B => Option[C]) => (A => Option[C]) = thenDo(f1) _
def thenDo[A, B, C](fa2ob: (A => Option[B]))(fb2oc: (B => Option[C])): (A => Option[C]) = { a =>
fa2ob(a) match {
case None => None
case Some(b) => fb2oc(b)
}
}
}
implicit def fToM[A, B](f: (A => Option[B])) = new Monadic(f)
def add1:(Int => Option[Int]) = x => Some(x+1)
def minus2:(Int => Option[Int]) = x => Some(x-2)
def div1:(Int => Option[Int]) = x => Some(x / 1)
def div0:(Int => Option[Int]) = x => None
-----------------------------------------
scala> val calc = add1 then minus2 then div1
calc: Int => Option[Int] = <function1>
scala> calc(5)
res0: Option[Int] = Some(4)
scala> val calc2 = add1 then div0 then add1 then minus2
calc2: Int => Option[Int] = <function1>
scala> calc2(5)
res1: Option[Int] = None
-----------------------but doesn't work on following definition-----
def add1m(i:Int) = Some(i + 2)
def minus2m(i:Int) = Some(i-2)
def div1m(i:Int) = i / 1
def div0m(i:Int) = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment