Clojure析构函数映射作为关键参数进行解析
我有一个关于两个功能的问题,一个是完整的地图,另一个是特定的关键字,如:Clojure析构函数映射作为关键参数进行解析,clojure,maps,keyword,optional-parameters,nested-map,Clojure,Maps,Keyword,Optional Parameters,Nested Map,我有一个关于两个功能的问题,一个是完整的地图,另一个是特定的关键字,如: (def mapVal {:test "n" :anotherKey "n"}) (defn functionTest [& {:keys [test anotherKey] :or {:test "d" :anotherKey "d"}}] (println :test :anotherKey)) (defn mapFunc [map] (functionTest (get-in map [:t
(def mapVal
{:test "n"
:anotherKey "n"})
(defn functionTest
[& {:keys [test anotherKey] :or {:test "d" :anotherKey "d"}}]
(println :test :anotherKey))
(defn mapFunc
[map]
(functionTest (get-in map [:test :anotherKey])))
目标是将参数映射中的所有键正确地传递给functionTest。不管怎样,这能奏效吗?我尝试了一些方法,但无法将所有关键字和值传递给functionTest。我不想要的只是映射的值,它应该通过关键字和值传递给另一个函数 你很接近。有几件事应该可以澄清 首先,当您使用
[&varname]
声明参数时,这意味着varname
将是一个包含所有额外参数的列表。因此,您不需要在这里使用“&
”来分解输入。相反,您只需指定希望成为变量的键
试试这个:
(defn functionTest
[{:keys [test anotherKey]}]
(println test anotherKey))
另一个问题是使用进入。使用get in
可以通过带有该向量的嵌套数据结构定义“路径”。例如,假设:
{:first {:a 1 :b 2} :second {:c 3 :d 4}}
您可以使用get in
获取:second
:c
处的值,方法如下:
(get-in {:first {:a 1 :b 2} :second {:c 3 :d 4}} [:second :c])
在您的情况下,根本不需要使用get-In
。你只需要通过整个地图。您在functionTest
中定义的分解将处理其余部分。以下是我所做的工作:
(defn mapFunc
[map]
(functionTest map))
我还建议您不要将该变量命名为“map
”,因为它与map
函数冲突。get in
用于访问嵌套的关联数据结构
(def m {:a {:x 1}})
(get-in m [:a :x]) ;;=> 1
在分解映射后,这些值在范围内,并通过符号进行访问。您的示例应该如下所示:
(def mapVal
{:test "n"
:anotherKey "n"})
(defn functionTest
[& {:keys [test anotherKey]
:or {:test "d" :anotherKey "d"}}]
(println test anotherKey))
(defn mapFunc
[m]
(apply functionTest (apply concat (select-keys m [:test :anotherKey]))))
(mapFunc mapVal) ;;=> prints: n n
您必须执行此操作,因为functionTest
接受裸键值对作为可选参数(位于&右侧的参数),如下所示:
选择关键点
返回仅包含指定关键点的地图:
(select-keys mapVal [:test])
;; => {:test "n"}
将concat
应用于地图将返回键和值的平铺序列:
(apply concat (select-keys mapVal [:test :anotherKey]))
;; => (:test "n" :anotherKey "n")
apply
将函数应用于seq,就像seq是其参数列表一样:
(+ [1 2 3]) ;;=> Error.
(apply + [1 2 3]) ;; => 6
作为旁注,在Clojure代码中,大多数名称的常规情况下,snake-case优先于camelCase
(+ [1 2 3]) ;;=> Error.
(apply + [1 2 3]) ;; => 6