简体   繁体   English

Clojure:使用{:keys [...]}进行结构化和重命名

[英]Clojure: destructure and rename with {:keys […]}

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: 但是,如果我想将1称为my-response ,我必须做以下事情:

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

Obviously this does not work with defn destructuring. 显然这不适用于defn解构。

Is there any way in Clojure to both destructure and rename keys? 在Clojure中是否有任何方法可以解构和重命名密钥?

Use destructuring without :keys : 使用解构而不:keys

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

{:keys [response]} is syntactic sugar for {response :response} . {:keys [response]}{response :response}语法糖。

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 . 有关更好的答案,请参阅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. 但这并不涉及任何复杂的解构。

If you don't mind using a library, a more powerful destructuring tool is available from tupelo.core/destruct . 如果您不介意使用库,可以从tupelo.core/destruct获得更强大的解构工具。 Here is an example: 这是一个例子:

(ns tst.demo.core
  (:use demo.core tupelo.core tupelo.test))

(dotest
  (let [info  {:a 777
               :b [2 3 4]}
        mania [{:a 11} {:b 22} {:c [7 8 9]}]]
    (let [z ::dummy]
      (destruct [info {:a z
                       :b [d e f]}
                 mania [{:a ?} BBB {:c clutter}]]
        (is= z 777)
        (is= [d e f] [2 3 4])
        (is= a 11)
        (is= BBB {:b 22})
        (is= clutter [7 8 9])))))

So you can see that inside the destruct expression, the symbols z , d , e , f , BBB , and clutter are given the corresponding values from the input variables info and mania . 因此,您可以看到在destruct表达式中,符号zdefBBBclutter从输入变量infomania中获得相应的值。 The special symbol ? 特殊符号? is interpreted to mean that the keyword :a creates a symbol a to receive the value 11 . 被解释为表示关键字:a创建符号a以接收值11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM