【问题标题】:Clojure: destructure and rename with {:keys [...]}Clojure:使用 {:keys [...]} 解构和重命名
【发布时间】:2019-08-21 12:37:08
【问题描述】:

是否可以一次性解构和重命名键?

考虑一下:

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

但是,如果我想将 1 称为 my-response,则必须执行以下操作:

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

显然这不适用于defn 解构。

Clojure 中是否有任何方法可以解构和重命名键?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    使用不带:keys的解构:

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

    {:keys [response]}{response :response} 的语法糖。

    【讨论】:

      【解决方案2】:

      给你:

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

      如需更好的答案,请参阅https://stackoverflow.com/a/57592661/2757027

      这个答案更接近问题,但从技术上讲不是一步。但这并不涉及任何复杂的解构。

      【讨论】:

        【解决方案3】:

        如果您不介意使用库,可以从tupelo.core/destruct 获得更强大的解构工具。这是一个例子:

        (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])))))
        

        所以您可以看到在destruct 表达式中,符号zdefBBBclutter 被赋予了来自输入变量的相应值infomania。特殊符号? 被解释为意味着关键字:a 创建了一个符号a 来接收值11

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-11-25
          • 1970-01-01
          • 2018-05-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多