## Monday, February 22, 2010

### Methods of PartialFunction object

This topic looks at the functionality provide in the object PartialFunction.

This example uses Scala 2.8 which I believe is required.

Only two methods are focused on. PartialFunction.cond and PartialFunction.condOpt.
As per request the signature for said methods are:
`def cond[T](x: T)(pf: PartialFunction[T, Boolean]): Booleandef condOpt[T, U](x: T)(pf: PartialFunction[T, U]): Option[U]`
Now for some examples:
`scala>  import PartialFunction._import PartialFunction._scala> def strangeConditional(other: Any): Boolean = cond(other) {     |  case x: String if x == "abc" || x == "def"  => true     |  case x: Int => true     | }strangeConditional: (other: Any)Booleanscala> strangeConditional("abc")res0: Boolean = truescala> strangeConditional("hello")res1: Boolean = falsescala> strangeConditional(3)      res2: Boolean = truescala> def onlyInt(v: Any): Option[Int] = condOpt(v) { case x: Int => x }onlyInt: (v: Any)Option[Int]scala> onlyInt("hi")res3: Option[Int] = Nonescala> onlyInt(3)res4: Option[Int] = Some(3)scala> import util.control.Exception.catchingimport util.control.Exception.catchingscala> object IntNum {      |  val number = catching(classOf[NumberFormatException])     |  def unapply(x : Any) = condOpt(x) {     |      case x : Int => x     |      case y : String if number.opt(y.toInt).isDefined => y.toInt     |    }     | }defined module IntNumscala> 1 match { case IntNum(x) => println(x+" i win!")}   1 i win!scala> 3 match { case IntNum(x) => println(x+" i win!")}3 i win!`

1. It would be somewhat more useful to supply the type signatures of cond and condOpt, I think. It's not necessarily obvious what the utility of these are, particularly when using Any for your examples; or rather, it's not clear what advantage is gained over using a simple match expression.

2. object IntNum {
..val number = catching(classOf[NumberFormatException])
..def unapply(x: Any) = x match {
....case x: Int => Some(x)
....case x: String => number.opt(x.toInt)
...._ => None
..}
}

is easier to read IMHO and does not call y.toInt twice (using opt together with condOpt seems contraproductive to me)

(sorry for the dots -- I was not able to figure out how to indent as tags are not allowed and whitespace is removed or compressed)

Nice blog, btw. Keep up the good work!

3. Wasn't it meant to be
scala> "3" match { case IntNum(x) => println(x+" i win!")}
3 i win!
?