A custom exercise that emphasizes Pattern Matching with Elixir.
Context
I am presenting Elixir to the software developers at my company during lunch hours. This is the exercise for session 2. For session 1, please refer to this post.
Session 2 was focused on Pattern Matching principles, as covered by chapter 3 of “Learn Functional Programming with Elixir”.
Exercise: Employee Info
My goal was show a realistic program with extensive use of pattern matching. I decided to create a custom implementation.
The program maintains a list of employee records. Originally the employee records are read from a CSV file, but then there is an interactive menu that allows records to be added, deleted, or changed.
- Exercise description & source code
The assignment is to understand the existing program, and then extend it by filling out the contents of these two functions:
Pattern Matching examples
These examples have been extracted from the above exercise.
First, pattern matching is used to parse the input file into an Employee structure:
Second, pattern matching is used to determine which get_unique_id/1
function is called:
Third, before saving the new employee data to disk, the employee structs are sorted by ID.
Guards are used to determine which sort_employee_data/1
function is called.
If the list only contains one record, then the length(employee_data) >= 2
check
will fail, and the second implementation will execute and return the list unchanged.
What makes this example interesting from a pattern matching perspective
is that the compare_ids/2
function only needs to extract the id
from each
structure. The entire structure gets sorted, but the rest of the fields
are not needed in the compare_ids/2
function logic.
Finally, pattern matching is used to find an particular struct among the list of employee records. This example demonstrates the pin operator.
Spotlight on the Pipeline Operator
The unit tests include the below snippets. When writing this code I was pleased with how clear the logic was, thanks to the expressiveness of the pipeline operator.
To setup an initial list of employee structs:
Later, when we change the data as part of a test:
Next session
The next session will focus on Recursion.