Elixir:使用模式匹配捕获地图的其余部分

时间:2015-05-15 16:41:56

标签: pattern-matching elixir

我想同时匹配地图中的特定键,捕获该地图的其余部分。我希望这样的东西能起作用:

iex(10)> %{"nodeType" => type | rest} = %{"nodeType" => "conditional", "foo" => "bar"}

** (CompileError) iex:10: cannot invoke remote function IEx.Helpers.|/2 inside match

目标是编写一组函数,在地图的某个字段上进行地图,模式匹配,并对地图的其余部分执行一些转换。

def handle_condition(%{"nodeType" => "condition" | rest}) do
  # do something with rest
done
def handle_expression(%{"nodeType" => "expression" | rest}) do
  # do something with rest
done

但看起来我需要被调用者单独传递nodeType,除非我遗漏了什么。

1 个答案:

答案 0 :(得分:13)

您可以轻松捕捉整个地图 - 也许这就足够了?

def handle_condition(all = %{"nodeType" => "condition"}) do
  # do something with all
end

或者:

def handle_condition(all = %{"nodeType" => "condition"}) do
  all = Map.delete(all, "nodeType")
  # do something with all
end