Return the args which are not passed as nil inside the function

85 Views Asked by At
(defn bar[{:keys [a b] :as args}] (prn "got" args))

If we are calling the above function as

(bar {:a 1})

it returns

{:a 1}
nil 

I want to have

{:a 1 :b nil}
2

There are 2 best solutions below

0
On

Not sure if it's worth the trouble, but you can get closer using the vals->map macro from the Tupelo library:

(defn whiffer
  [{:keys [a b]}]
  (vals->map a b) )

with result:

(whiffer {:a 1, :b 2})  => {:a 1, :b 2}
(whiffer {:a 1})        => {:a 1, :b nil}
0
On

I don't think this can be done without changing the implementation of Clojure's destructuring code. Is below satisfactory?

user=> (defn bar [{:keys [a b]}] (prn "got" {:a a, :b b}))
#'user/bar
user=> (bar {:a 1})
"got" {:a 1, :b nil}