nótaí de devos

Querying a Dataset with Scala's Pattern Matching

This post is about matching patterns against collections, combining patterns in interesting ways and defining patterns in terms of other patterns. Patterns defined in this way look and feel like a lightweight, domain specific query language. Very little supporting code is required.

A Dataset and a Query

Here are some collections representing a genealogy (their contents are given at the end):

For this particular example the pattern matching expression seems clearer. To be fair, it did require us to define some extractors first. As the examples grow more complicated, the pattern matching approach looks prettier.

Traversals and Filters

The Parents and Children extractors yield collections. If we want to compose, say, Children with Children to extract grandchildren we must be able to match across collections. We can overload unapply to accept collections:

Here the implicit Flattener determines how to combine a collection of matches into a result. The implementation is omitted for brevity, but assume that failed matches are ignored and matches yielding sets are merged into a union. Other types of matches are returned as-is in a collection.