Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: destructure and rename with {:keys [...]}

Tags:

clojure

Is it possible to both destructure and rename keys in one go?

Consider this:

(let [{:keys [response]} {:response 1}]
  (println response))

However, if I want to instead refer to 1 as my-response, I have to do something like:

(let [{:keys [my-response]} (clojure.set/rename-keys {:response 1} {:response :my-response})]
  (println my-response))

Obviously this does not work with defn destructuring.

Is there any way in Clojure to both destructure and rename keys?

like image 901
user1338062 Avatar asked Aug 21 '19 12:08

user1338062


2 Answers

Use destructuring without :keys:

(let [{my-response :response} {:response 1}]
  (println my-response))

{:keys [response]} is syntactic sugar for {response :response}.

like image 71
Erwin Rooijakkers Avatar answered Oct 19 '22 20:10

Erwin Rooijakkers


Here you go:

(let [{:keys [response]} {:response 1}
      my-response response]
   (println my-response))

For a better answer refer to https://stackoverflow.com/a/57592661/2757027.

This answer is much closer to the question, but technically not single step. but this doesn't involve any complicated de-structuring.

like image 36
Mrinal Saurabh Avatar answered Oct 19 '22 20:10

Mrinal Saurabh