Create a map having a key as a variable

I have a key as a variable, I want to create a Map with a key :key1 or “key2” using one of the variables, but I’m unable to:

iex(24)> a1 = :key1
:key1
iex(25)> a2 = "key2"     
"key2"
iex(26)> %{a1: 123}
%{a1: 123}
iex(27)> %{:a1 => 123}
%{a1: 123}
iex(28)> %{^a2 => 123}
** (CompileError) iex:28: cannot use ^a2 outside of match clauses
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
iex(28)> %{^a1 => 123}
** (CompileError) iex:28: cannot use ^a1 outside of match clauses
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
1 Like

Don’t use the ^, just put a1 => 123 for it. :slight_smile:

2 Likes

You only use the pin operator ^ inside a match. It is used where you want to match on the value bound to the variable, and not bind a value to the variable.

iex(1)> a = 5
5
iex(2)> a = 7
7
iex(3)> ^a = 7
7
iex(4)> ^a = 5
** (MatchError) no match of right hand side value: 5
1 Like