Search code examples
clojurehashmap

How to pass all key value pairs of a hashmap into a function (without passing the whole hashmap)?


I want to pass in all the key-val pairs of a hashmap into a function, but not the whole hashmap.

So I have a function I can't change that looks something like this:

(defn foo [a b c & {:keys [x y z]}]
  (println x y z))

I have a hashmap that will have a variable amount of keys and values. Let's say one instance will be:

(def bar {:d 1
          :e 2
          :x "x"
          :y "y"})

How do I call pass in all the key-value pairs into foo without passing the whole hashmap? I want to do

(foo "a" "b" "c" 
     :d 1
     :e 2
     :x "x"
     :y "y")

Solution

  • select-keys can be used to prune a map to desired keys:

    (apply foo "a" "b" "c" (apply concat (select-keys bar [:x :y :z])))
    

    Alternatively, a cheeky workaround is to use Clojure 1.11.0-alpha1 or later which supports keyword arguments to be passed as maps. With this you can simply do:

    (foo "a" "b" "c" bar)