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

D. *_*uke 15 elixir pattern-matching

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

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

** (CompileError) iex:10: cannot invoke remote function IEx.Helpers.|/2 inside match
Run Code Online (Sandbox Code Playgroud)

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

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

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

Paw*_*rok 14

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

def handle_condition(all = %{"nodeType" => "condition"}) do
  # do something with all
end
Run Code Online (Sandbox Code Playgroud)

要么:

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


pot*_*bas 5

实现此目的的另一个好方法是使用Map.pop/2

def handle(%{} = map), do: handle(Map.pop(map, "nodeType"))

def handle({"condition", rest}) do
  # ... handle conditions here
end

def handle({"expression", rest}) do
  # ... handle expressions here
end
Run Code Online (Sandbox Code Playgroud)