Clojure-创建嵌套地图

时间:2018-10-01 20:18:37

标签: clojure

我想创建一个嵌套地图。

我拥有的函数实现如下:

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

谢谢。

2 个答案:

答案 0 :(得分:1)

clojure.core中有一个assoc-in函数,您可以使用此函数。 assoc-in采用关联数据结构(例如地图,矢量),键路径序列以及要在嵌套路径的 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

答案 1 :(得分:0)

与许多语言不同,clojure允许您使用集合文字作为函数的返回值,而不会产生额外的开销,因此例如,创建嵌套映射的函数可能很简单

<select  multiple="multiple" name="religion[]">
     @foreach($religion_data as $religion)
          <option value="{{$religion->religion_id}}" @if($profile_data->p_religion == $religion->religion_id) selected @endif>
               {{$religion->religion_name}}
          </option>
     @endforeach
</select>

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

(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}}) namestr

相关问题