Skip to content

Instantly share code, notes, and snippets.

@sofoklis
Last active December 11, 2015 20:48
Show Gist options
  • Save sofoklis/4657634 to your computer and use it in GitHub Desktop.
Save sofoklis/4657634 to your computer and use it in GitHub Desktop.
partialfunctions.scala
// Full definition by defining the abstract methods
val pf1 = new PartialFunction[Int, Int]{
def apply(x: Int): Int = x match { case t if isDefinedAt(t) => t + 1 }
def isDefinedAt(x: Int): Boolean = x > 0 && x < 10
} //> pf1 : PartialFunction[Int,Int] = <function1>
pf1.isDefinedAt(20) //> res0: Boolean = false
//pf1(20) //scala.MatchError
//pf1.apply(20) // same as above using aply method
pf1.isDefinedAt(9) //> res1: Boolean = true
pf1(9) //> res2: Int = 10
// Same definition using case
val pf: PartialFunction[Int, Int] =
{ case x if(x > 0 && x < 10) => x + 1 } //> pf : PartialFunction[Int,Int] = <function1>
pf.isDefinedAt(20) //> res3: Boolean = false
//pf(20)//scala.MatchError:
pf.isDefinedAt(9) //> res4: Boolean = true
pf(9) //> res5: Int = 10
// Creates a regular functions that returns None if the function is not defined at the argument
val liftedPf1 = pf1 lift //> liftedPf1 : Int => Option[Int] = <function1>
liftedPf1(9) //> res6: Option[Int] = Some(10)
liftedPf1(20) //> res7: Option[Int] = None
// one regular function
val f = (x: Int) => x //> f : Int => Int = <function1>
// Apply uses the partial functino if it is difined at the argument
pf1 applyOrElse (4, f) //> res6: Int = 5
// or the argument function otherwise
pf1 applyOrElse (30, f) //> res7: Int = 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment