PartialFunction in Scala

by 1/05/2012 04:51:00 PM 0 comments
From: Weblogs Forum - Scala, Patterns and The Perl Effect

I came across this comment thread on Bruce Eckel's blog. Trond Olsen's comments provided an 'aha' moment that helped me understand PartialFunctions:

Partial functions are defined for specific value ranges. The example just showed how you can compose two partial functions, one on {"1","2","3"} and another on {1,2,3}, into one of the union of those. Partial functions gives a runtime error when you hit outside their defined value ranges.

And here's the code:

val f1: PartialFunction[Any,String] = {
  case "1" => "One"
  case "2" => "Two"
  case "3" => "Three"
}

val f2: PartialFunction[Any,String] = {
  case 1 => "One"
  case 2 => "Two"
  case 3 => "Three"
}

val f3 = f1 orElse f2

f3("1")
// res0: String = One

f3(1)
// res1: String = One

f3("3")
// res2: String = Three

f3("a")
// scala.MatchError: a (of class java.lang.String)

And here's further extension of the example:

val f4: PartialFunction[Any,String] = {
  case _ => "undefined"
}

val f5 = f3 orElse f4

f5("a")
// res3: String = undefined




Update July 2013:

And here's a great answer on Stackoverflow that describes "lifting". Lifting is a way to convert a partial function to a function that returns an Option. For values in the range that a PartialFunction accepts a lifted function will return Some; for values outside it's range a lifted PartialFunction will return None.

hohonuuli

Developer

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

0 comments: