我在编写函数子句时遇到问题,我需要对映射进行模式匹配,并保留它以便在函数中使用.我无法理解语法是什么.基本上我想要这样的东西:
def check_data (arg1, %{"action" => "action1", ...}, arg2) do
# access other keys of the structure
end
Run Code Online (Sandbox Code Playgroud)
我确信这是非常基本的,但这似乎是在逃避我.我已经阅读了很多教程,但似乎无法找到一个处理这个用例的教程.
Dog*_*ert 11
要匹配地图的某些键并将整个地图存储在变量中,您可以使用= variable以下模式:
def check_data(arg1, %{"action" => "action1"} = map, arg2) do
end
Run Code Online (Sandbox Code Playgroud)
此函数将匹配包含"action1"键中的任何映射"action"(以及任何其他键/值对)作为第二个参数,并将整个映射存储在map:
iex(1)> defmodule Main do
...(1)> def check_data(_arg1, %{"action" => "action1"} = map, _arg2), do: map
...(1)> end
iex(2)> Main.check_data :foo, %{}, :bar
** (FunctionClauseError) no function clause matching in Main.check_data/3
iex:2: Main.check_data(:foo, %{}, :bar)
iex(2)> Main.check_data :foo, %{"action" => "action1"}, :bar
%{"action" => "action1"}
iex(3)> Main.check_data :foo, %{"action" => "action1", :foo => :bar}, :bar
%{:foo => :bar, "action" => "action1"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3193 次 |
| 最近记录: |