We can now write a little library that enables us to write dynamic match specs and we can use the atom names of records (index and path) and the function with make_ms to make a dymamic match spec which will always be right at run time:

We can now write a little library that enables us to write dynamic match specs and we can use the atom names of records (index and path) and the function with make_ms to make a dymamic match spec which will always be right at run time:

Author

Overview

This How To shows how dynamic match specifications can be built using records.

This approach allows record definitions to be extended by adding new fields, or the order of fields in records to be amended, without affecting the dynamic match specifications.

It works by generating a helper library function at compile time which enables a match_specifications module to introspect the record structure and build dynamic match specs.

The Problem

Records are a great way of making tuples easier to handle - they are the Erlang equivalent of a C struct. The ability to reference an element in a structure without having to know it is the third element is great, but...

...the problem is that sometimes you actually need to know the structure - and the main time is when you want to write match specifications.

There is a 'work around' for writing transforming code that has records in it but which generates valid match specs. This uses the function fun2ms from stdlib (see the documentation [1]).

But the problems with fun2ms is that it can't take a variable so you *can* use it to make writing static match specifications easier but you *can't* use it to generate them dynamically.

You might think the answer is to use fun2ms within an eval but you don't have access to the record definition in an eval so you are snookered there too..

The Solution

The solution is to use the Erlang Preprocessor to parse the .hrl file that has the record definition and output a helper function.

This helper function must be generated everytime the header file is changed as part of the make procedures for you application.

Dynamic match specifications written with the library will then 'just work'!

Writing Dynamic Match Specs

We can now write a little library that enables us to write dynamic match specs and we can use the atom names of records (index and path) and the function with make_ms to make a dymamic match spec which will always be right at run time: