Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is match a language feature?

I'm teaching myself Scala and I have sort of a philosophical question. Is pattern matching a language feature of Scala, or just a library feature? To put it another way, could I, were I sufficiently skilled, write xmatch, a function that was identical to match in every way except the name? Actually, I think those are two slightly different questions: is matching a library feature, and could it be a library feature?

I was thinking of trying to re-write match, purely as an exercise, but I wanted some assurance it was possible.

like image 903
Michael Lorton Avatar asked Dec 21 '22 18:12

Michael Lorton


2 Answers

Pattern matching is a language feature, of which the match statement is only 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 can't do that on your own. The language does not allow you to define new ways to create variables, so these things can only happen with language support.

The match statement itself uses the pattern-matching variable-creation support inside the language, but otherwise could in principle be implemented as a library feature. However, it would be inefficient in several cases:

// 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, all in all, no, you can't write pattern matching yourself, and while you could write the match statement, there are advantages in using the existing one.

like image 161
Rex Kerr Avatar answered Dec 25 '22 23:12

Rex Kerr


Actually, match used to be implemented in the library, I've heard. The Change Log in the Scala Reference indicates match became a reserved keyword on version 2.0, at which point object.match { ... } ceased to be a valid syntax as well.

It is rather easy to implement it in principle:

implicit def toMyMatch[T](obj: T) = new {
    def myMatch[R](f: T => R) = f(obj)
}

I don't know the exact reasons why it ceased to be implemented this way.

like image 24
Daniel C. Sobral Avatar answered Dec 25 '22 22:12

Daniel C. Sobral