shorter_maps
shorter_maps copied to clipboard
~m{a: 1} generates atom instead of string
thanks for the library. i had my homegrown thing which wasn't half as powerful.
there's a bug when using alt names:
iex> Mix.install([:decimal, {:shorter_maps, "~> 2.0"}])
iex> import ShorterMaps
iex> ~m{a}
%{"a" => 1}
iex> ~m{a: 1}
%{a: 1}
So in ~m{a}
the key will be a string and in ~m{a: 1}
the key will be an atom.
i dug through the code (tests more specifically) and found that the syntax that does work is ~m{"a" => 1}
. i'm going to assume this is the best approach and not dig in to "fix" this.
Hi, sorry to have missed you while this was open and you were struggling.
I'm not 100% clear what your initial goal was: if you want the map %{:a => 1}
, then you should just use the standard Elixir atom shorthand notation of %{a: 1}
The goal of shortermaps is when your variable names correspond to the keys of a map; so if you had:
iex> a = 1
...> ~M{a}
%{:a => 1}
# -or-
...> ~m{a}
%{"a" => 1}
in short, ~M
is for atom keys, and ~m
is for string keys.
Please feel free to re-open if you think there's an issue to fix here.
oh no, i did indeed supply a bad example that didn't explain my motive.
i want to pattern match. let's say there's an incoming map like
a = %{"a" => 1, "b" => 2}
i want to extract both keys, but if b
is already in use i need to rename it. so i'd like to go
~m{a, b: alt_b} = a
I'm expecting that sigil to return a map with two string keys, but actually alt_b
is an atom.
# translated to
%{"a" => a, b: alt_b} = a
does this make more sense?
edit: I did at one point figure out by reading the tests that the expected syntax for this is ~m{a, "b" => alt_b}
. but this isn't very intuitive and it's undocumented. but if this syntax is on purpose then i guess it's just a documentation issue.