Shorthand pattern matching for maps

43 views
Skip to first unread message

Gustavo Honorato

unread,
Aug 10, 2019, 10:54:29 AM8/10/19
to elixir-l...@googlegroups.com
Hello Everyone! I'm following Elixir community for a long time and recently I decided to start my first Elixir project, and I'm really enjoying it. Thanks for bringing us this awesome tool.

I noticed that many times I write the following pattern matching for maps:

 test "test descritption", %{var_a: var_a, var_b: var_b} do
# Test case here
end

This happens mostly on test cases and it's really boring. My suggestion is to add a shorthand matcher (like the shorthand object destruction in Javascript). The test case could be rewritten like:

 test "test descritption", %{var_a, var_b} do
# Test case here
end

Kindly regards,
Gustavo

Justin Wood

unread,
Aug 10, 2019, 11:01:14 AM8/10/19
to elixir-l...@googlegroups.com
There has been a lot of conversation around something like this in the
past[1][2]. I'm sure there are other examples as well.

If I recall properly, the short answer to this proposal is no, unless
someone can come up with a new spin to it. The languages that have this
feature generally have a single data type to worry about (strings). In
Elixir, we have strings and atoms to consider when attempting a match
like this.

[1]
https://elixirforum.com/t/proposal-add-field-puns-map-shorthand-to-elixir/15452
[2]
https://groups.google.com/forum/#!searchin/elixir-lang-core/short$20hand$20maps%7Csort:date/elixir-lang-core/XxnrGgZsyVc/KgJwV8e-CgAJ

W-M Code

unread,
Aug 13, 2019, 4:11:41 AM8/13/19
to elixir-lang-core
And if memory serves right, there exist a couple of libraries that implement shorthand map syntax, which means that it is even less likely to be added to the core language.

For instance there is shorter_maps which uses the `~M` sigil to build shorter maps, which would make your example: `~M{var_a, var_b}`.
I believe there are other libraries that do something similar as well.

~Marten/Qqwy
Reply all
Reply to author
Forward
0 new messages