Clojure destruct map解析为关键参数

时间:2016-05-27 22:30:43

标签: 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 [:test :anotherKey])))

目标是将参数映射中的所有键正确传递给functionTest。反正这有用吗?我尝试了一些东西,但我不能将所有的关键字和值传递给functionTest。我不想要的只是地图的值,它应该传递给具有关键字和值的其他函数。

2 个答案:

答案 0 :(得分:1)

你非常接近。有些事情应该清除它。

首先,当您使用[& varname]声明参数时,表示varname将是包含所有额外参数的列表。因此,您不需要使用' &'在这里解构输入。相反,您只需命名要成为变量的键。

试试这个:

(defn functionTest
 [{:keys [test anotherKey]}]
 (println test anotherKey))

另一个问题是使用get-in。使用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函数冲突。

答案 1 :(得分:0)

(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

你必须经历这个,因为(functionTest :test "n" :anotherKey "n" ) ;;=> Also prints: n n 接受裸键值对作为可选参数(&右边的那些),如:

select-keys

(select-keys mapVal [:test]) ;; => {:test "n"} 返回仅包含指定键的地图:

concat

(apply concat (select-keys mapVal [:test :anotherKey])) ;; => (:test "n" :anotherKey "n") 应用于地图会返回一系列平键和值:

apply

(+ [1 2 3]) ;;=> Error. (apply + [1 2 3]) ;; => 6 将一个函数应用于seq,就好像seq是它的参数列表一样:

Starting JS server...
Building and installing the app on the device (cd android && ./gradlew installDebug...
Downloading https://services.gradle.org/distributions/gradle-2.4-all.zip

Exception in thread "main" javax.net.ssl.SSLHandshakeException: 

sun.security.validator.ValidatorException: PKIX path building failed: 

sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

作为旁注,传统上在Clojure代码中,对于大多数名字来说,蛇案比camelCase更受欢迎。