Pattern Maching in Programming Languages
Several functional programming languages (e.g. Scala, Haskell, and ML) support pattern matching of data objects. Recently Martin Odersky, the designer of Scala, explained pattern matching.
In a recent interview with Bill Venners at Artima.com Martin Odersky explained how pattern matching works in Scala, and what its role is.
It is impossible to argue that pattern matching isn't useful to programmers. Especially to those writing compilers. But I don't agree as Martin says, that it is essential. I think he realizes this, and it was just a mild exageration. In the world of compiler writing, after you have gotten used to pattern matching, it is very painful to go back.
I do however have one issue with pattern matching: the deconstruction of objects is coupled with the construction of the object. I don't believe that the consumer of data (e.g. objects) should care about how that data is produced or structured. Otherwise, we can't make changes to the production of the objects, without affecting the consumption. In other words: these concerns are coupled.
So what should a language designer do?
Well I am thinking that maybe we can have pattern matching, and decouple it from object construction and data layout by having objects expose a single function which returns a tuple representing the data layout to be matched on.
So for example in an XML tree, an XML node might have a function with the signature "deconstruct() : List<XMLNode>" which could be used in pattern matching statements.
This way the actual layout of data in the XML node class, won't affect pattern matching. We are minimizing the point of contact between the pattern matching and the class.
The only other idea I have is introducing a type switch statement into the langauge. This would allow programmers to replace:
if (x is A)
f(x as A);
else if (x is B)
g(g as B);
With the following code
case (A) :
case (B) :
Arguably this is a poor man's pattern matching, but maybe it is still an improvement over nothing, even if it isn't as powerful as Scala pattern matching.