Search code examples
clojure

In Clojure, how to destructure all the keys of a map?


In clojure, it is possible to destructure some keys of a map like this:

(let [{:keys [cpp js]} {:cpp 88 :js 90}] 
   (println js); 90
   (println cpp); 88
 )

Is there a way to destructure all the keys of a map?

Maybe something like:

(let [{:all-the-keys} {:cpp 88 :js 90}] 
   (println js); 90
   (println cpp); 88
 )

Solution

  • Not really, and it wouldn't be a good idea. Imagine:

    (let [{:all-the-keys} m]
      (foo bar))
    

    Are foo and bar globals? Locals? Keys you should extract from m? What should this code do if m sometimes contains a foo key, and foo is also a global function? Sometimes you call the global, and sometimes you call the function stored in m?

    Ignoring the technical problems (which could be overcome), it is really a disaster for readability and predictability. Just be explicit about what keys you want to pull out; if you frequently want to pull out the same ten keys, you can write a simple macro like (with-person p body) that simplifies that common case for you.