Pattern matching is a language function, of which the match operator is just the most notable example. Here are two other commonly used examples:
val List(x,y,(z: Int,w: Int)) = List("one","two",(3,4)) for ((text,i) <- List(("one",1),("two",2))) println(text + " = " + i)
So no, you cannot do it yourself. The language does not allow you to define new ways to create variables, so these things can only happen with the support of the language.
The match operator itself uses template creation support that supports the template inside the language, but in principle it can be implemented as a library function. However, in some cases this would be ineffective:
// This is implemented with fast jumps, not slow if-then-else! n match { case 0 => // Do action 0 case 1 => // Do action 1 case 2 => // Do action 2 case _ => // Do default action } // This is tail recursive, so you won't overflow the stack! def recursiveMatch(xs: List[Any]): List[Any] = xs match { case (x @ Int) :: rest => recursiveMatch(rest) case _ => xs }
So, in general, no, you cannot write a template that matches yourself, and although you can write a matching operator, there are advantages to using an existing one.
source share