[Request/Discussion] Reducing boilerplate in struct pattern match

If you tried pattern match as struct and assign values to variables, you have to repeat the variable name.

def f(%Line{length: length, x: x, y: y}) do

You can end up typing the name three times if you do a pattern match with the value which is rather annoying

def f(%Line{type: type = %Type{}, length: length, ...}) do

What about an alternate syntax with a variable name matches the structure key:

def f(%Line{type = %Type{}, length, ...}) do

This will reduce the variable name duplication a little bit, reducing amount of typing you have to do - unless you want to name the variable something else, then you would have to resort to the current syntax, or use the struct.key syntax.

def f(%Line{type: type1 = %Type{}, length: length1}, %Line{type: type2 = %Type{}, length: length2}) do
# or 
def f(line1 = %Line{}, line2 = %Line{}) do
  line1.type ...

I am not a fan of the implicit binding of variables, but there is shorter_maps on hex.pm which implements some of your proposals on top of a sigil. It has some technical limitations though (you need to use a different set of delimeters for each level of nesting).

3 Likes