A use case for match?/2 in Elixir
1 min readAug 10, 2018
Sometimes I come across code where an map (or tuple) is being tested against a pattern to return a boolean result; like this:
That works fine, but can be simplified by using the Kernel.match?/2
function:
Like when using other (more famous)Kernel
functions such as ==/2
, to_string/1
, and send/2
, the "Kernel"
prefix can be omitted leaving us with a clean one-line statement.
Here is a silly “real-world” example which shows that you can also use guard clauses in your match expression:
Lastly, if you are just testing for one (or maybe two) conditions in a map, keep things simple and stick with a simple Map.get/3
: