Is language function matching?

I teach myself Scala, and I have a philosophical question. Is matching a Scala language function template or just a library? In other words, can I, if I were experienced enough, write xmatch , which was identical to match in all respects except the name? Actually, I think these are two slightly different questions: is the library function consistent and can it be a library function?

I thought about trying to rewrite the match, just like an exercise, but I wanted to get some confidence that this was possible.

+4
source share
3 answers

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.

+5
source

Actually, match used in the library, I heard. The change log in the Scala Reference indicates that match became a reserved keyword in version 2.0, after which point object.match { ... } no longer valid syntax.

This is pretty easy to implement in principle:

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

I do not know the exact reasons why it ceased to be implemented in this way.

+4
source

Pattern matching is definitely a language feature. However, since writing flow control structures to Scala is so simple (and pattern matching is reliable), you can easily write your own match (compared to other languages).

match , on the other hand, is still part of the core of the language (I think), but it behaves much more like something in a library. It is so organic because of how strong the pattern matching is.

However, you could rewrite match .

+2
source

Source: https://habr.com/ru/post/1337893/


All Articles