如何将哈希图的所有键值对传递给函数(不传递整个哈希图)?

Bri*_*anN 0 clojure hashmap

我想将哈希映射的所有键值对传递到函数中,但不是整个哈希映射。

所以我有一个我无法改变的功能,看起来像这样:

(defn foo [a b c & {:keys [x y z]}]
  (println x y z))
Run Code Online (Sandbox Code Playgroud)

我有一个哈希图,它将具有可变数量的键和值。假设一个实例是:

(def bar {:d 1
          :e 2
          :x "x"
          :y "y"})
Run Code Online (Sandbox Code Playgroud)

如何在不传递整个哈希图的情况下将所有键值对调用传递到 foo 中?我想要做

(foo "a" "b" "c" 
     :d 1
     :e 2
     :x "x"
     :y "y")
Run Code Online (Sandbox Code Playgroud)

Ste*_*ott 5

select-keys 可用于将映射修剪为所需的键:

(apply foo "a" "b" "c" (apply concat (select-keys bar [:x :y :z])))
Run Code Online (Sandbox Code Playgroud)

或者,一个厚脸皮的解决方法是使用 Clojure1.11.0-alpha1或更高版本,它支持作为 maps 传递的关键字参数。有了这个,你可以简单地做:

(foo "a" "b" "c" bar)
Run Code Online (Sandbox Code Playgroud)