2013-08-01 41 views
3

我正在通過一本關於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))) 
+1

這裏有一個提示:你的'camel-pairs-> map'函數沒有對傳入的參數's'做任何事情。 – Alex

回答

6

三個問題:缺少一個括號,缺少的camel->keyword名義>,而不是「播種」你->>宏觀與初始表達s

(defn camel-pairs->map [s] 
    (->> s 
     (map-indexed 
     (fn [i x] 
      (if (odd? i) 
      x 
      (camel->keyword x)))) 
     (apply hash-map))) 

這真的比說更清楚嗎?

(defn camel-pairs->map [s] 
    (into {} 
    (for [[k v] (partition 2 s)] 
     [(camel->keyword k) v]))) 
+0

不,這是一個更清晰的方法。我還沒有接觸到'進入'或'分區'。唉,這就是爲什麼我越來越喜歡clojure:「總有一種更好的方式。」 – Clev3r

+0

@Clever 4clojure是你的朋友!至少獲得所有簡單和基本的完成.. –

相關問題