Tuesday, March 2, 2010

Methods on PartialFunction

This topic inspects the methods defined in the PartialFunction Object.
  1. scala> type PF = PartialFunction[Int,Int]
  2. defined type alias PF
  3. // the two partial functions that we will use for the examples
  4. scala> val pf1 : PF = {case 1 => 2}                      
  5. pf1: PF = < function1>
  6. scala> val pf2 : PF = {case 2 => 3}                      
  7. pf2: PF = < function1>
  8. /*
  9. As is well known, when a PartialFunction is called with a value
  10. it must be defined at that value or bad things will happen
  11. */
  12. scala> pf1 isDefinedAt 1  
  13. res14: Boolean = true
  14. scala> pf1 isDefinedAt 2
  15. res15: Boolean = false
  16. scala> pf1(2)
  17. scala.MatchError: 2
  18. at $anonfun$1.apply(< console>:5)
  19. at $anonfun$1.apply(< console>:5)
  20. at .< init>(< console>:7)
  21.     ...
  22. scala> pf1(1)
  23. res5: Int = 2
  24. /*
  25. It is possible to compose two partial functions so first one partialFunction is called and then the next
  26. */
  27. scala> (pf1 andThen pf2) isDefinedAt 2 
  28. res16: Boolean = false
  29. scala> (pf1 andThen pf2) isDefinedAt 1
  30. res17: Boolean = true
  31. scala> (pf1 andThen pf2)(2)
  32. scala.MatchError: 2
  33. at $anonfun$1.apply(< console>:5)
  34. at $anonfun$1.apply(< console>:5)
  35. at scala.PartialFunction$$anon$2.apply(PartialFunction.scala:59)
  36. at .< init>(< console>:8)
  37.     ...
  38. scala> (pf1 andThen pf2)(1)
  39. res8: Int = 3
  40. /*
  41. An alternative way of combining PartialFunctions is to 'or' them
  42. */
  43. scala> (pf1 orElse pf2) isDefinedAt 1
  44. res18: Boolean = true
  45. scala> (pf1 orElse pf2) isDefinedAt 2
  46. res19: Boolean = true
  47. scala> (pf1 orElse pf2) isDefinedAt 3
  48. res20: Boolean = false
  49. scala> (pf1 orElse pf2)(1) 
  50. res9: Int = 2
  51. scala> (pf1 orElse pf2)(2)
  52. res10: Int = 3
  53. /*
  54. Finally a PartialFunction can be easily converted to a function that returns 
  55. an Option
  56. */
  57. scala> pf1.lift
  58. res21: (Int) => Option[Int] = < function1>
  59. scala> pf1.lift(1)
  60. res11: Option[Int] = Some(2)
  61. scala> pf1.lift(2)
  62. res12: Option[Int] = None

3 comments:

  1. Why is the method returning Option called "lift"?

    ReplyDelete
  2. In all honesty I don't know. But like most programmers I can make up reasons :)

    I would first say that it is based on functional programming terminology. I would say it comes from "lifting" a partial function to a full function. But that is speculation

    ReplyDelete
  3. I think that "lift" is a term for putting a value into a monad. And Option[T] is a monad.

    ReplyDelete