She sells sea shells : Pattern matching records

author by Shayne Fletcher August 22, 2019

In this article

This is a brief survey of possibilities when pattern matching records in Daml.

This will help those looking to learn about features enabling succinct expressions involving records as arguments.

We start with the following data declaration to give us something to work with.

Suppose we want to write a function that calculates the number of items on a stack.

Consider the “canonical” way of writing this function where we attempt to be as explicit as possible.

2-1

[Note : Rule of thumb for formatting “with” blocks - Always indent under the ‘with’ and always drop back when the block is finished.]


Daml allows us to inline the function’s type signature like this.3-1

“Record field punning” (meaning, when the name of the variable coincides with the name of the field, you can omit it) is supported so we can remove the bindings of variable names and work directly with the field labels.3.1-1

The field top is unused so we can elide matching on it.4-1We can rewrite the above as a multi-equation equivalent (and we’ll drop the explicit type annotation for brevity).4.1

We can get the second equation down to a “one-liner” by switching to “record brace” syntax.


Lastly, we can employ “record wild cards” in the second equation to bring the field labels of the argument into the scope of the right hand side so that we can write simply this.


Daml provides flexibility for expressing patterns over records allowing the modeler to find their own “right” balance between readability and conciseness!