繁体   English   中英

Clojure惯用解决方案将变量作为map返回

[英]Clojure idiomatic solution to return variables as map

我正在学习clojure,我非常喜欢它。 但是我来自emacs-lisp背景,在解构时我仍然有点困惑。 目前,我收到了一个包含大量密钥的数据库查询。 我通过解构将它们分解为不同的变量,最后,在通过let创建几个新值之后,我将哈希映射重建为返回值。 代码如下所示:

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

这只是一个提取,下面有许多不同的条件。 所以有很多代码对我来说完全没用。 我想这很丑陋,肯定不是应该的样子。 有关如何做到这一点的任何建议吗? 任何帮助将深表感谢!

你可以这样捕捉整个地图:

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}

因此,您只需更新地图中的某些特定值,而无需重新定义。 另请参阅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))

你看,现在你甚至可以删除grammartrans :keys vector,因为你不再需要它们了

暂无
暂无

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

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