Pattern matching in multi level nested maps

How do I pattern match in multi-level nested maps

Suppose this is my map , 
mymap = %{a: "xxx" , b: %{k1: "k1" , k2: "k2" , c: %{k3: "k3", k4: "k4"}}}

When I do this , I get an  error , 

** %{a: v1, b: %{k1: v2, k2: v3, c: %{k3: v4, k4: v4}}} = mymap **

** (MatchError) no match of right hand side value: %{a: "xxx", b: %{c: %{k3: "k3", k4: "k4"}, k1: "k1", k2: "k2"}}
    (stdlib) erl_eval.erl:453: :erl_eval.expr/5
    (iex) lib/iex/evaluator.ex:257: IEx.Evaluator.handle_eval/5
    (iex) lib/iex/evaluator.ex:237: IEx.Evaluator.do_eval/3
    (iex) lib/iex/evaluator.ex:215: IEx.Evaluator.eval/3
    (iex) lib/iex/evaluator.ex:103: IEx.Evaluator.loop/1
    (iex) lib/iex/evaluator.ex:27: IEx.Evaluator.init/4

You ask here that :k3 and :k4 have values that meatch.

2 Likes

Extremely sorry for the typo , if I extend to below

mymap = %{a: "xxx" , b: %{k1: "k1" , k2: "k2" , c: %{k3: "k3", k4: "k4"}, d: %{k5: "k5", k6: "k6"}}}

Here "b" has multiple sub maps within it , the below pattern match fails ,

%{a: v1, b: %{k1: v2, k2: v3, c: %{k3: v4, k4: v4}, d: %{k5: v5, k6: v6}}} = mymap 
** (MatchError) no match of right hand side value: %{a: "xxx", b: %{c: %{k3: "k3", k4: "k4"}, d: %{k5: "k5", k6: "k6"}, k1: "k1", k2: "k2"}}
    (stdlib) erl_eval.erl:453: :erl_eval.expr/5
    (iex) lib/iex/evaluator.ex:257: IEx.Evaluator.handle_eval/5
    (iex) lib/iex/evaluator.ex:237: IEx.Evaluator.do_eval/3
    (iex) lib/iex/evaluator.ex:215: IEx.Evaluator.eval/3
    (iex) lib/iex/evaluator.ex:103: IEx.Evaluator.loop/1
    (iex) lib/iex/evaluator.ex:27: IEx.Evaluator.init/4

How do I pattern match if there are multiple sub maps within a map ?

you still didn’t fix the typo. You ask that k3: and k4: both have the same value v4 but then pass "k3" and "k4 as the values. Your pattern is OK, your data simply doesn’t match.

1 Like

Again, like Noobz wrote you need k3 and k4 values to be the same here. You need another variable vX to match k4 values if it has to be distinct from k3’s

Apologies , it was indeed the typo causing the issue :weary: