带可选键的模式匹配映射

时间:2014-07-16 08:22:20

标签: elixir

我有一个函数接收带有许多键的映射,其中一些是可选的。如何编写理解地图的函数签名,同时允许可选键默认为某些内容?

def handle_my_map(%{text: text, 
                    print_times: print_times, # this I want to default to 2
                    color: color # this I want to default to "Blue"
  }) do
  Enum.each(1..print_times, fn (_) -> IO.puts ["(", color, "): ", text] end)
end

Test.handle_my_map(%{text: "here", print_times: 5, color: "Red"})
# (Red): here
# (Red): here
# (Red): here
# (Red): here
# (Red): here

handle_my_map(%{text: "there"})
# => MatchError!

我希望它是:

handle_my_map(%{text: "where", print_times: 3})
# (Blue): where
# (Blue): where
# (Blue): where
handle_my_map(%{text: "there"})
# (Blue): there
# (Blue): there

像ruby的关键字参数:

def handle_my_map(text: nil, print_times: 2, color: 'Blue')

3 个答案:

答案 0 :(得分:12)

您可以使用Map.merge/2

defmodule Handler do
  @defaults %{print_times: 2, color: "Blue"}

  def handle_my_map(map) do
    %{text: text, print_times: times, color: color} = merge_defaults(map)
    Enum.each(1..times, fn (_) -> IO.puts ["(", color, "): ", text] end)
  end

  defp merge_defaults(map) do
    Map.merge(@defaults, map)
  end
end

如果您想允许nils,可以使用Map.merge/3并将merge_defaults/1更改为:

defp merge_defaults(map) do
  Map.merge(@defaults, map, fn _key, default, val -> val || default end)
end

答案 1 :(得分:3)

我可能会这样做:

defmodule Handler do
  @defaults %{print_times: 2, color: "Blue"}

  def handle_my_map(map) do
    %{text: text, print_times: times, color: color} = Dict.put_new(map, @defaults)
    Enum.each(1..times, fn (_) -> IO.puts ["(", color, "): ", text] end)
  end
end

如果您需要使用现有密钥处理nil值,您可以执行以下操作:

defmodule Handler do
  @defaults %{print_times: 2, color: "Blue"}

  def handle_my_map(map) do
    %{text: text, print_times: times, color: color} = @defaults
    |> Dict.merge(map)
    |> Enum.into %{}, fn
      {key, nil} -> {key, @defaults[key]}
      {key, val} -> {key, val}
    end

    Enum.each(1..times, fn (_) -> IO.puts ["(", color, "): ", text] end)
  end
end

答案 2 :(得分:1)

好。我认为你需要用参数handle_my_map编写另一个%{a: a, b: b}函数。像这样:

  def handle_my_map(%{a: a, b: b, optional_c: c}) do
    a + b + c
  end

  def handle_my_map(%{a: a, b: b}) do
    a + b
  end

  YourModule.handle_my_map %{a: 1, b: 2}
  #=> 3
  YourModule.handle_my_map %{a: 1, b: 2, optional_c: 3}
  #=> 6

Elixir将搜索与您的参数匹配的函数handle_my_map,直到具有arity 1的函数结束