Pattern matching


Once a month I drive up to Oakland to attend the SF Bay Groovy and Grails Meetup organized by Chris Richardson. It’s a fun group of people and conversation covers a lot of ground. During Monday’s meeting we chatted about Scala, among other things, and how it was good for pattern matching in exactly the way that object-oriented solutions weren’t.

Chris gave the example of dispatching requests in a web server by matching URI patterns to discover what internal methods to call to handle requests. Scala’s switch statement allows a URI to be split into a list of tokens (as do many other languages) and then makes it easy to match against this list, even if the list is not homogeneous. It furthermore makes the matching values available to the closure handling the case, making it more expressive than (for example) Java.

This made me reflect on when pattern matching is used versus more explicit representations of structure. For example, when making a function call, we rely on an explicit (simple) declared structure rather than on a sequential examination of possible patterns to decide what function to call. (Overloaded methods don’t really require serious pattern matching.) So pattern matching is typically used when the input is poorly structured, natural language processing being a good example. While the utility of using plain text URIs as a lingua franca among heterogeneous systems is compelling, but I found it ironic that, in a sense, that the URI, the basis of internet communication, winds up being treated more like natural language than a function call.