2016-09-27 37 views
3

我在编写函数子句时遇到了困难,我需要对映射进行模式匹配,并保留它以便在函数中使用。我无法理解语法是什么。基本上我想要这样的事情:模式匹配映射作为函数参数

def check_data (arg1, %{"action" => "action1", ...}, arg2) do 
    # access other keys of the structure 
end 

我确信这是非常基本的,但它似乎是躲避我。我已经阅读了许多教程,但似乎找不到能够处理此用例的人。

+1

你是指像'DEF check_data(%{ “动作”=> “动作1”} = ARG1,ARG2) '或'def check_data(arg1,%{“action”=>“acti on1“} = arg2)'? – Dogbert

+0

@Dogbert不,不。我的意思是说除地图外还有其他的论点。我们可以在函数参数中使用'arg1 =%{}'吗? :O – dotslash

+2

因此'def check_data(arg1,%{“action”=>“action1”} = map,arg2)'?是的,你可以在函数参数中使用'='。 – Dogbert

回答

8

要匹配地图的一些关键,也是整个地图存储在一个变量,你可以使用= variable与图案:

def check_data(arg1, %{"action" => "action1"} = map, arg2) do 
end 

此功能将匹配任何包含在关键"action""action1"地图(和任何其它的键/值对)作为第二参数,并且整个地图存储在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"}