Feature Request: Destructuring Maps

249 views
Skip to first unread message

Sheharyar Naseer

unread,
Jun 1, 2017, 3:04:01 AM6/1/17
to elixir-lang-core
Most Elixir devs will agree with me, that when pattern matching on Maps, the variable names are usually the same as the keys:

def some_method(%{user: %{id: id, email: email}, action: action, message: message}) do
 
# do something
end


I propose another way to pattern match Key-Value pairs in Maps, using the variable names alone (Similar to how you destructure objects in ES6):

%{ a, b } = %{a: 1, b: 2}

and

def some_method(%{user: %{ id, email }, action, message}) do
 
# do something
end

If this makes sense to others, I'm can try doing this and send a PR (if someone can point me in the right direction 😊).

FTS

unread,
Jun 1, 2017, 4:51:21 AM6/1/17
to elixir-l...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-core+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/1d79fb43-8385-46d2-b4c9-8acca1c2407f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

José Valim

unread,
Jun 1, 2017, 9:29:39 AM6/1/17
to elixir-l...@googlegroups.com
This discussion comes up from time to time, so I would recommend seeing the previous discussions. There are many in favor of this feature and many that do not appreciate the loss in readability.

Although I have almost no reservations against using a shorthand syntax for matching, I find it too cryptic for creates:

%{name, age} #=> %{name: name, age: age}

And even more for updates:

%{user | name, age} #=> %{user | name: name, age: age}

The choice is in supporting the syntax only for matching but that makes the feature somewhat inconsistent.



José Valim
Skype: jv.ptec
Founder and Director of R&D

Sheharyar Naseer

unread,
Jun 1, 2017, 2:27:03 PM6/1/17
to elixir-lang-core, jose....@plataformatec.com.br
Personally I like the "create" and "update" shorthand syntaxes, but I guess that goes against the goal of writing explicit elixir code. As for those against it, I find their argument weak since every developer/team is open to following their own style guides without anyone forcing them to do otherwise but I do get where they are coming from.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages