【问题标题】:In Elixir, why is Kernel.put_in/3 defined in the Kernel module rather than the Map module?在 Elixir 中,为什么 Kernel.put_in/3 定义在 Kernel 模块而不是 Map 模块中?
【发布时间】:2020-10-23 02:54:50
【问题描述】:

在 Elixir 中更新嵌套 Map 中的值时,我们可以使用 Kernel.put_in/3

map = %{hi: "what's", up: %{my: "boii"}}
%{hi: "what's", up: %{my: "boii"}}

Kernel.put_in(map, [:up, :my], "dawg") 
%{hi: "what's", up: %{my: "dawg"}}

考虑到它们的输入和结果非常相似,为什么不将这个函数与Map.put/3 一起定义?

【问题讨论】:

    标签: elixir


    【解决方案1】:

    Kernel.put_in 函数适用于任何具有访问行为的结构,根据它的文档:

    @spec put_in(Access.t(), nonempty_list(term), term) :: Access.t()
    def put_in(data, [_ | _] = keys, value) do
      elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1)
    end
    

    Maps 和 Keyword 列表都支持访问行为,因此 put_in 不是 Maps 独有的,因此位于 Kernel 模块中。

    关键字列表中的使用示例:

    iex(1)> Kernel.put_in([foo: 3], [:foo], 4)
    [foo: 4]
    iex(2)> Kernel.put_in([foo: [bar: 3]], [:foo, :bar], 4)
    [foo: [bar: 4]]
    

    【讨论】:

      猜你喜欢
      • 2016-11-12
      • 2020-04-10
      • 2019-06-01
      • 2019-11-13
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 2017-05-28
      相关资源
      最近更新 更多