簡體   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