dictionaryclojurekeyword-argumentdestruction

Clojure applying a map and keyword arguments destruction


Consider a function with the following signature:

(defn make-widget [& {:keys [x y] :or {x 10 y 20}}]
 ...)

What is the best way to pass a map to the function, e.g.:

(make-widget {:x 100})

or

(make-widget {:y 200 :x 0})

What I have currently thought of is via vec, flatten and apply e.g.:

(apply make-widget (flatten (vec ({:x 100}))

I strongly believe there is a better way to do this. Can you please consider one?


Solution

  • For anyone reading this after 2021, since Clojure 1.11 you can pass a map to a function directly (in the way the original question wished for). No need to do any extra work!

    (defn make-widget [& {:keys [x y] :or {x 10 y 20}}]
      [x y])
    
    (make-widget :x 1) ; => [1 20]
    (make-widget {:x 100}) ; => [100 20]
    (make-widget {:y 200 :x 0}) ; => [0 200]
    

    For more details, see the original announcement at https://clojure.org/news/2021/03/18/apis-serving-people-and-programs