【发布时间】:2014-07-16 08:22:19
【问题描述】:
我有一个函数可以接收带有许多键的地图,其中一些是可选的。如何编写理解映射的函数签名,同时允许可选键默认为某些东西?
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')
【问题讨论】:
-
这个
handle_my_map/1接受一个参数? -
@Зелёный - 是的,一个地图参数
标签: elixir