繁体   English   中英

Clojure-创建嵌套地图

[英]Clojure - Create Nested map

我想创建一个嵌套地图。

我拥有的函数实现如下:

(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的新手。

谢谢。

clojure.core中有一个assoc-in函数,您可以使用此函数。 assoc-in采用关联数据结构(例如,地图,矢量),键路径序列和要在嵌套路径末端关联的值。

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

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

因此,您可以使用asil作为第一个参数,根据assoc-in定义函数:

(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映射文字使用关键字键,尽管许多其他类型也可以正常使用,并且可以将它们混合使用:

(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

与许多语言不同,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}})

如果需要将数字添加到传入的关键字的末尾,则可以使用有用的函数来处理关键字。它们是name strkeyword

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM