Johan Lundberg
Johan Lundberg

Reputation: 27088

matching a key of type map in map with elixir

Learning Elixir basics I tried tried this, which does what I expect,

gg=%{:a => 1, 2 => :b, %{ :a => 5 } => 8}

gg[:a]   # give 2
%{ :a => k } = gg # gives k = 2

gg[%{ :a => 5 }] # gives 8

but what's the specific problem with this:

%{ %{ :a => 5 } => k } = gg

The error I get is

** (CompileError) hello.exs:46: only association operators '=>' are 
allowed in map construction
    (stdlib) lists.erl:1338: :lists.foreach/2
    (elixir) lib/code.ex:363: Code.require_file/2

What's going on?

Upvotes: 2

Views: 69

Answers (1)

raacer
raacer

Reputation: 5481

Looks like a bug in Elixir. Same works fine in Erlang.

1> M = #{ #{1 => 2} => 10 }.
#{#{1 => 2} => 10}
2> #{ #{1 => 2} := X } = M.
#{#{1 => 2} => 10}
3> X.
10

As a workaround you can use variable for key:

iex(1)> key = %{a: 5}
%{a: 5}
iex(2)> %{ ^key => v } = gg
%{2 => :b, :a => 1, %{a: 5} => 8}
iex(3)> v
8

I've created bug report here: https://github.com/elixir-lang/elixir/issues/5602

Upvotes: 3

Related Questions