【问题标题】:Clojure - Create Nested mapClojure - 创建嵌套地图
【发布时间】:2018-10-01 20:18:37
【问题描述】:

我想创建一个嵌套地图。

我的功能实现如下:

(defn thefunction [something value]

;;"something" is for i.e: (something2 something3) ;it's a seq, could have more values.

;;here I want the code to create a map like this >> {:something2 {:something3 value}}

我不知道如何实现它以获取上面的地图。我是 clojure 的新手。

谢谢。

【问题讨论】:

  • 您可以使用 assoc-in 来实现这一点:(assoc-in nil [:foo :bar] 1) => {:foo {:bar 1}}
  • @TaylorWood 我想使用 (get-in theMap [:something2 :something3]) 访问该值,但它返回 nil 因为它保存 {something2 {something3 value}} 而不是 {:something2 {: something3 值}}
  • @AgustínP。欢迎来到 Stack Overflow,我真的很高兴你从观看到发帖。你知道你可以通过在行首放四个空格来格式化你的代码片段吗?如果您包含对您正在编写的函数的示例调用,以及您认为输出的样子,它也会更容易回答。这样我就不会猜到错误的期望输出。
  • @marco.m 作业问题没有错。这就是问题的提出方式。

标签: clojure


【解决方案1】:

clojure.core 中有一个assoc-in 函数可以用于此目的。 assoc-in 采用关联数据结构(例如 map、vector)、key-path 序列和要在嵌套路径的 end 处关联的值。

在您的情况下,没有可关联的预先存在的结构,但这很好,因为assoc-in 在内部使用assoc,如果第一个参数为 nil,它将创建一个映射:

(assoc nil :foo 1)
=> {:foo 1}

因此,您可以根据assoc-in 定义您的函数,并将 nil 作为其第一个参数:

(defn the-function [something value]
  (assoc-in nil something value))

例如,如果您的 something 序列由符号组成:

(the-function '(something2 something3) 'value)
=> {something2 {something3 value}}

(the-function (map str (range 4)) :foo)
=> {"0" {"1" {"2" {"3" :foo}}}}

我想使用 (get-in theMap [:something2 :something3]) 访问该值,但它返回 nil

通常您会看到 Clojure 映射文字使用 keyword 键,尽管许多其他类型也可以正常工作,并且可以混合使用:

(the-function [:foo "bar" 'baz] \z)
=> {:foo {"bar" {baz \z}}}

您可以在调用函数之前将输入序列转换为关键字(如果您想为所有调用者强制执行关键字键,则可以在函数内部)。

(the-function (map keyword '(something2 something3)) 'value)
=> {:something2 {:something3 value}}
(get-in *1 (map keyword '(something2 something3)))
=> value

【讨论】:

    【解决方案2】:

    与许多语言不同,clojure 允许您使用集合字面量作为函数的返回值,而无需额外开销,因此例如创建嵌套映射的函数可以像

    (defn i-make-a-nested-map []
     {1 {:a {:b 2}}})
    

    并且可以在其中的任何地方使用函数的参数:

    (defn i-make-a-nested-map [I'm-a-function-argument]
     {1 {:a {:b I'm-a-function-argument}}})
    

    所以你的问题几乎包含了你写的答案:

    (defn thefunction [something value]
        {:something2 {:something3 value}})
    

    如果您需要在传入的关键字末尾添加数字,则有一个有用的关键字操作函数。它们是namestrkeyword

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-18
      • 2016-11-14
      • 2012-07-19
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2020-04-26
      • 2021-06-16
      相关资源
      最近更新 更多