在地图上的模式匹配与变量作为关键

时间:2016-09-08 05:30:32

标签: elixir

如何在具有字符串键的地图上进行模式匹配?

iex(1)> my_map = %{"key1" => "var1"}
%{"key1" => "var1"}
iex(2)> %{aa => bb} = my_map
** (CompileError) iex:2: illegal use of variable aa inside map key match, maps can only match on existing variable by using ^aa
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
iex(2)> %{"aa" => bb} = my_map
** (MatchError) no match of right hand side value: %{"key1" => "var1"}

2 个答案:

答案 0 :(得分:5)

如果地图保证只有一个条目(就像您在评论中澄清的那样),您可以将其传递给Map.to_list/1,然后对结果进行模式匹配:

iex(1)> my_map = %{"key1" => "var1"}
%{"key1" => "var1"}
iex(2)> [{key, value}] = Map.to_list(my_map)
[{"key1", "var1"}]
iex(3)> key
"key1"
iex(4)> value
"var1"

答案 1 :(得分:1)

对于使用 理解http://elixir-lang.github.io/getting-started/comprehensions.html

,可以使用一个或多个条目的地图

Phoenix flash消息作为带有字符串键的映射存储在conn中,如下所示:

%{"info" => "Please check the content", "notice" => "No search results"}

这是我在框架中的layout_view.ex:

defmodule MyAppWeb.LayoutView do

  use MyAppWeb, :view

  ...

  #https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#sigil_E/2
  #https://hexdocs.pm/phoenix/Phoenix.Controller.html#get_flash/1

  def show_flash(conn) do
    Phoenix.Controller.get_flash(conn)
    |> flash_msg()   
  end

  def flash_msg(messages) when map_size(messages) >= 1 do    
    for { key, msg } <- messages do
      content_tag(:div, class: "mapapp-alert myapp__#{key}") do
        [ msg,
          content_tag(:span, ~E"&times;", class: "myapp-closebtn", onclick: "this.parentElement.style.display='none';")
        ]
      end
    end   
  end

  def flash_msg(_) do
    nil   
  end

end