eitan
eitan

Reputation: 59

destructuring a map as function input

let us say that I have a simple map

(def mymap {:a 1 :b 2 :c 3 :d 4})

Now I want to write a function called get-c. This function will get mymap as the input. Now since I am only interested in :c is there way to only get c already during the input stage? I have tried many variations but I always get an error. e.g.

(defn get-c [[{:keys [c]} input-map]] c) 

It does compile but when I try (get-c mymap) I get

IllegalArgumentException Parameter declaration "mymap" should be a vector  clojure.core/assert-valid-fdecl/fn--7207 (core.clj:7187)

Thanks. Eitan

Upvotes: 1

Views: 432

Answers (3)

Pardeep Singh
Pardeep Singh

Reputation: 422

Destructing Maps in Clojure is a very convenient and powerful feature. You can destruct the keys, rename the keys and also provide default values for keys.

(defn destruct-test
  [{:keys [name company]
    :as zmap
    :or {name "Default Name"
         company "Default Company"}}]
  [name company])

Upvotes: 0

Kyle Grierson
Kyle Grierson

Reputation: 346

(defn get-c [{:keys [c]}] c) 

You added too many [] so clojure was trying to destruct a vector.

Upvotes: 3

Anton Chikin
Anton Chikin

Reputation: 1836

(defn get-c [{c :c}] c)

Here is a good reference for destructuring.

Upvotes: 0

Related Questions