2015-05-07 34 views
0

假設我有這樣的如何將字符串集合成一個字符串,並將其添加到前面的位置?

(def base ["one" "two" "three"]) 

我想將其轉換爲:

1. one 
2. two 
3. three 

(又名1. one \n2. two \n3. three

join,我不知道在加入之前,我可以追加一個計數器:

(clojure.string/join " \n" base) 
=> "one \ntwo \nthree" 

doseq或相似,加上一個原子,我得到各個琴絃,但屆時將有來連接以後,像

(def base ["one" "two" "three"]) 

(def pos (atom 0)) 

(defn add-pos 
    [base] 
    (for [b base] 
    (do 
     (swap! pos inc) 
     (str @pos ". " b)))) 

(let [pos-base (add-pos base)] 
    (clojure.string/join " \n" pos-base)) 

=> "1. one \n2. two \n3. three" 

雖然它的工作原理,如果使用原子與for我不知道聲明是他做這件事的最好方式,它看起來並不是很酷的。

請問有更好的方法嗎?

回答

4

這對keep-indexed工作:

user> (keep-indexed #(str (inc %1) ". " %2) ["one" "two" "three"]) 
("1. one" "2. two" "3. three") 
user> (clojure.string/join "\n" 
     (keep-indexed 
      #(str (inc %1) ". " %2) 
      ["one" "two" "three"])) 
"1. one\n2. two\n3. three" 
+0

太棒了!看起來clojure具有很多功能,而我最大的問題是發現/發現這些功能! – LocustHorde

+1

除了SO之外,您可以註冊4clojure,然後查看其他人在您做的時候所做的解決方案 - 可用於核心Clojure的API發現以及查看何時/何地可以使用某些功能 – lispHK01

+1

使用keep -indexed'對傳遞給它的lambda返回的每個值進行邏輯真值檢查,最終將其忽略。這種檢查在這種情況下完全沒有用處,因此不必要的開銷。 'map-indexed'就足夠了。 –

3

A小調替代schaueho我們保持索引將map-indexed(看上一個模式?)

(def base ["one" "two" "three"]) 

(defn numbered-list [s] 
    (->> s 
     (map-indexed #(str (inc %1) ". " %2)) 
     (interpose \newline) 
     (apply str))) 

(numbered-list base) ; => "1. one\n2. two\n3. three" 
+0

謝謝,我瞭解了'interpose'和'\ newline'! – LocustHorde

3

很明顯的一個工作,interleave

(->> (interleave (rest (range)) (repeat ". ") base (repeat " \n")) 
    (apply str)) 

;-> "1. one \n2. two \n3. three \n" 
+0

..很聰明,謝謝! – LocustHorde

相關問題