我正在通過一本關於clojure的書,並用「 - >>」遇到了一個絆腳石。作者提供了一個comp
的示例,該示例將camelCased
關鍵字轉換爲clojure映射,並使用更具慣用意義的camel-cased
方法。下面的代碼使用補償:「 - >>」宏和迭代函數應用程序
(require '[clojure.string :as str])
(def camel->keyword (comp keyword
str/join
(partial interpose \-)
(partial map str/lower-case)
#(str/split % #"(?<=[a-z])(?=[A-Z])")))
這使得有很大的意義,但我真的不喜歡使用partial
所有的地方來處理可變數量的參數。相反,另一種方法是在這裏提供:
(defn camel->keyword
[s]
(->> (str/split s #"(?<=[a-z])(?=[A-Z])")
(map str/lower-case)
(interpose \-)
str/join
keyword))
這句法是更可讀,並模仿我會去想解決問題的方式(從前到後,而不是回到前面)。擴展comp
完成上述目標...
(def camel-pairs->map (comp (partial apply hash-map)
(partial map-indexed (fn [i x]
(if (odd? i)
x
(camel->keyword x))))))
什麼會使用->>
是相同呢?我不確定如何使用->>
線索映射索引(或任何迭代函數)。這是錯誤的:
(defn camel-pairs->map
[s]
(->> (map-indexed (fn [i x]
(if (odd? i)
x
(camel-keyword x)))
(apply hash-map)))
這裏有一個提示:你的'camel-pairs-> map'函數沒有對傳入的參數's'做任何事情。 – Alex