type | rest} = %{"nodeType" -6ren">
gpt4 book ai didi

pattern-matching - Elixir:使用模式匹配捕获 map 的其余部分

转载 作者:行者123 更新时间:2023-12-03 20:30:04 24 4
gpt4 key购买 nike

我想同时匹配 map 中的特定键,捕获该 map 的其余部分。我希望这样的事情会起作用:

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

最佳答案

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

关于pattern-matching - Elixir:使用模式匹配捕获 map 的其余部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30264656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com