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

Elixir: Capturing the rest of a map using pattern matching

我想同时匹配地图中的特定键,捕获该地图的其余部分。我希望这样的事情会奏效:

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 除非我遗漏了什么。

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

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

另一种实现此目的的好方法是使用 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