繁体   English   中英

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

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

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

考虑一下:

(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中是否有任何方法可以解构和重命名密钥?

使用解构而不:keys

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

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

干得好:

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

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

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

如果您不介意使用库,可以从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

暂无
暂无

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

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