View Source Extructure (Extructure v0.2.1)
Implementation of the <~
extructure operator.
Link to this section Summary
Functions
Destructures the right hand side expression into and according to the left side expression.
Link to this section Functions
Destructures the right hand side expression into and according to the left side expression.
Supports destructure-like implicit keys (with the same name as the variable) as well as optional variables, flexible keyword and key-pair tuple size and order of elements, implicit transformations between a map, list and a key pair tuple.
Also supports toggling between the loose mode and the standard Elixir pattern matching ("rigid") mode where none of the flexibilities are allowed.
Fully enforces pattern matching between the left and the right side once taken into account the optional variables and structural transformation.
Features
Optional variables - Prefix the variable name with an underscore and/or declare it as a function with zero arguments. If used, the underscore is trimmed from the variable's name e.g. an
_a
is translated toa
.Optional variables - Declare the variable as a function taking the default value as its single argument.
In the loose (default) mode use maps, keywords and key-pair tuples interchangeably as you see fit.
Toggle the loose mode into the rigid mode by using the unary
^
operator left to a map, list or tuple that requires Elixir-like pattern matching. If requiring a loose matching again at a nested level in the structure, use the^
operator again to toggle back to loose and so on.To match typical tuples or non-keyword lists, switch to the rigid mode with the
^
operator, if only for the tuple in question.
For nesting, use the keys as you would in plain Elixir matching:
%{ a: %{ b}} <~ [ a: %{ b: 2}]
# a variable is not set
# b variable is set to 2
or
%{ a: a = %{ b}} <~ [ a: %{ b: 2}]
# both a and b variables are set
Note
Variables with specified keys must be placed (in a keyword list) trailing the ones without the explicit keys:
%{ a, b, c: c, d: _d} <~ %{ a: 1, b: 2, c: 3}
or
[ a, b, c: c, d: _d] <~ %{ a: 1, b: 2, c: 3}
Any errors in the left-side expression are detected in compile time.
Usage
Instead of:
%{
first_name: fist_name,
last_name: last_name,
} = socket.assigns
age = socket.assigns[ :age]
simply use:
%{ first_name, last_name, _age} <~ socket.assigns
or
{ first_name, last_name, _age( 25)} <~ socket.assigns
or
[ first_name, last_name, age( 25)] <~ socket.assigns
See the README.md
and extructure_test.exs
files for more examples.