Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure maps to named keys syntax

Tags:

clojure

I'm guessing there's a simple way to do this that I'm not finding. I want to pass a map to a method that takes named values bound to keys, e.g.

(defn my-method [ & {:keys [ a b c ] }] ...

This works if called with e.g.

(my-method :a 1 :b 2 :c 3)

but I'd like to call it with a supplied map, e.g. something that looks like

(def m {:a 1 :b 2 :c 3})

(my-method m)

Is there a simple method to transform the map to the required argument list?

like image 706
Steve B. Avatar asked Feb 09 '26 18:02

Steve B.


2 Answers

It ain't pretty but:

(apply my-method (mapcat identity m))

or as suggested in the comments:

(apply my-method (apply concat m))
like image 133
Alex Miller Avatar answered Feb 15 '26 16:02

Alex Miller


Just drop the ampersand:

> (defn my-method [{:keys [a b c]}] (+ a b c))
> (my-method m)
6
like image 22
Tom Smilack Avatar answered Feb 15 '26 17:02

Tom Smilack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!