Model matching maps as function arguments

I had problems writing functional sentences, where I need to map a template to a map and save it for use in a function. I can't figure out what the syntax is. Basically I want something like this:

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

I am sure it is very simple, but it is what seems to elude me. I went through a lot of tutorials, but I can't seem to find the one that handles this use case.

+4
source share
1 answer

To map some map keys and save the entire map in a variable, you can use = variablewith a template:

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

, "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"}
+9

Source: https://habr.com/ru/post/1655946/


All Articles