His tip cleans up the examples in post Chaining Partial Functions with orElse
The secret is to define the type alias
type =>?[-A, +B] = PartialFunction[A, B]
. This alias may be added to Predef in the future but until it is you can add it yourself.- scala> type =>?[-A, +B] = PartialFunction[A, B]
- defined type alias $eq$greater$qmark
- scala> val i : (Any =>? Unit) = {case x:Int => println("int found")}
- i: =>?[Any,Unit] = < function1>
- scala> val j : (Any =>? Unit) = {case x:Double => println("Double found")}
- j: =>?[Any,Unit] = < function1>
- scala> val * : (Any =>? Unit) = {case x=> println("Something else found")}
- *: =>?[Any,Unit] = < function1>
- scala> (i orElse j orElse *)(1)
- int found
- scala> (i orElse j orElse *)(1.0)
- Double found
- scala> (i orElse j orElse *)(true)
- Something else found
- scala> def =>?[A, B](id : A =>? B) = id
- $eq$greater$qmark: [A,B](id: =>?[A,B])=>?[A,B]
- scala> ( =>?[Any, Unit]{case s : String => println("String found")} orElse j orElse *)("hello")
- String found
A nice alias indeed, but with one trap. The built-in => is right associative whereas the one defined above will be left associative. This is one reason why the latter was removed from Predef after making it in there at one stage.
ReplyDeleteTo make what inkytonik said clearer, consider this:
ReplyDeleteA => B => C
A =>? B =>? C
They translate, respectively, into:
Function1[A, Function1[B, C]]
PartialFunction[PartialFunction[A, B], C]
It looks like if you add a : that changes the associativity:
ReplyDeletescala> type =>?:[-A, +B] = PartialFunction[A, B]
defined type alias $eq$greater$qmark$colon
scala> class X { val x : Int =>?: Unit =>?: Any = null }
defined class X
scala> new X().x
res2: =>?:[Int,=>?:[Unit,Any]] = null
I still say that =?> scans better visually. And it has embedded meaning: if you pass this to something that's expecting a Function1, you may have a nice mushroom cloud in the middle of things!
ReplyDelete