ES6-ish "property value shorthands" for maps?

Is there any discussion about adding something similar to ES6 “property value shorthands” to maps? I’m just getting started with elixir so I’m not sure where to look for this type of language discussion.

What do you think about the idea? Would it be possible?

In Java Script (ES6) one can create an object like this:

let x = 50;
let y = 100;

let coordinates = { x, y };

which is shorthand for:

var coordinates = { x: x, y: y }

It would be great to have some thing similar in elixir:

iex> fu = "bar"
"bar"

iex> %{fu}  # Shorthand for %{fu: fu}
%{fu: "bar"}

and it could be used to bind variables in matches:

fn(%{x, y})  # Shorthand for fn(%{x: x, y: y})
2 Likes

Library is already made that does all that (in both atom and string key variants): https://hex.pm/packages/short_maps ^.^

EDIT: Sadly it is an all or nothing right now, no mixing short and long form, which really sucks in some cases, but it is a feature that ‘could’ be added to it if someone were to PR it perhaps? Would also be cool to make the atom/string choosing direct so :something maps to an atom and something does a string key match instead of the trailing modifier.

3 Likes

I was surprised to learn Elixir doesn’t support this as it seems similar to pattern matching. @josevalim why is this?

Thaks for pointing me to the library @OvermindDL1!

Also found a link to a discussion on the elixir mailing list on the short_maps librarys github page.

There was actually a huge conversation about this with jose a while back at: Redirecting to Google Groups

EDIT: @anders beat me to the link. ^.^

On an aside, I’d love this syntax or:

iex> %{:a, "b", :c => d, 'e', f: %{:g}} = {a: 1, "b" => 2, c: 3, 'e' => 4, f: %{g: 5}}
iex> a
1
iex> b
2
iex> c
** (CompileError) iex:25: undefined function c/0
iex> d
3
iex> e
4
iex> g
5

It would be able to handle all the basic types for anything from phoenix param matching to erlang strings to atoms to going back to normal pattern matching. Even if this were as a sigil maybe like m%{:a, "b", :c => d, 'e', f: m%{:g}} or something. Could have a base case of an undecorated variable fall back to being just an atom (the default case), and support adding ^ to any of them to match an equal named variable.

Perhaps it’s because I’m new to elixir (and not used to seeing sigils), but the “undecorated” style is much more appealing to me. This feature is all about reducing character noise and repetition and, to me, the sigils introduce another kind of noise that makes the code less fluent to read.