我目前正在学习clojure,我非常喜欢它。然而,我来自 emacs-lisp 背景,在解构方面我仍然有点困惑。 目前我收到一个包含很多键的数据库查询。我通过解构将它们分解为不同的变量,最后,在通过 let 创建了几个新值之后,我重建了一个 HashMap 作为返回值。 代码如下所示:
(fn [{:keys [metre _id num filedate divtype section sandhi lines grammar devanagari filename notes trans sectionnumber fileauthor lang]}]
(cond
;;when we have chinese
(= lang "zh")
(let [newgrammar (apply str (map (fn [{:keys [word position line tag] }]
(str "<span class=\"dropt\">" word
"<span style=\"width:500px;\"><font color=\"green\">Word:</font>" word
"<br><font color=\"red\">Function:</font> " tag
"<br><font color=\"blue\">Meaning:</font> " (db/get-chindic-meaning word tag)
"</span></span>")) grammar))
newtrans (first (map #(last (last %)) trans))]
(hash-map :metre metre :id _id :num num :filedate filedate :divtype divtype :section section :sandhi sandhi :lines lines :grammar newgrammar :devanagari devanagari :filename filename :notes notes :trans newtrans :sectionnumber sectionnumber :fileauthor fileauthor :lang lang))
这只是一个摘录,后面还有很多不同的条件。所以有很多代码对我来说完全没有必要。 我想这很丑陋,而且肯定不是应该的样子。关于如何正确执行此操作的任何建议?任何帮助将不胜感激!
最佳答案
你可以这样捕捉整个 map :
user> (defn my-fun [{:keys [a b c d e] :as params-map}]
(assoc params-map
:a 200
:b 100))
#'user/my-fun
user> (my-fun {:a 1 :b 2 :c 3 :d 4 :e 5})
{:a 200, :b 100, :c 3, :d 4, :e 5}
因此您只需更新 map 中的某些特定值,而无需重新定义它。
还可以查看 update
,在这种情况下它可能会有用
至于我,我会这样重写你的 fn:
(移出部分功能,使用update
)
(defn update-grammar [grammar]
(apply str (map (fn [{:keys [word position line tag] }]
(str "<span class=\"dropt\">" word
"<span style=\"width:500px;\"><font color=\"green\">Word:</font>" word
"<br><font color=\"red\">Function:</font> " tag
"<br><font color=\"blue\">Meaning:</font> " (db/get-chindic-meaning word tag)
"</span></span>")) grammar)))
(defn update-trans [trans] (first (map #(last (last %)) trans)))
(fn [{:keys [metre _id num filedate divtype section
sandhi lines grammar devanagari filename
notes trans sectionnumber fileauthor lang]
:as params-map}]
(cond
;;when we have chinese
(= lang "zh")
(-> params-map
(update :grammar update-grammar)
(update :trans update-trans))
你看,现在你甚至可以从 :keys
向量中删除 grammar
和 trans
,因为你不再需要它们了
关于variables - 返回变量作为 map 的 Clojure 惯用解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35151763/