2016-09-27 38 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"}