2014-09-05 15 views
3

是否有可以替換子序列的函數?例如:替換子序列的函數

user> (good-fnc [1 2 3 4 5] [1 2] [3 4 5]) 
;; => [3 4 5 3 4 5] 

我知道有clojure.string/replace字符串:

user> (clojure.string/replace "fat cat caught a rat" "a" "AA") 
;; => "fAAt cAAt cAAught AA rAAt" 

是否有向量和列表類似的東西?

回答

1

這是一個可以和懶惰seq輸入很好地玩的版本。請注意,它可以採用無限延遲序列(range),而無需循環無限循環版本。

(defn sq-replace 
    [match replacement sq] 
    (let [matching (count match)] 
    ((fn replace-in-sequence [[elt & elts :as sq]] 
     (lazy-seq 
     (cond (empty? sq) 
      () 
       (= match (take matching sq)) 
       (concat replacement (replace-in-sequence (drop matching sq))) 
       :default 
       (cons elt (replace-in-sequence elts))))) 
    sq))) 

#'user/sq-replace 
user> (take 10 (sq-replace [3 4 5] ["hello, world"] (range))) 
(0 1 2 "hello, world" 6 7 8 9 10 11) 

我把製作序列參數的最後一個參數的自由,因爲這是Clojure中的約定對於行走序列的功能。

+0

它已被修復,謝謝。 – noisesmith 2014-09-07 05:22:23

+1

我用'(應用str(sq-replace「a」「AA」「胖貓抓到一隻老鼠」))測試了我的解決方案(後來證明這是一個僞裝)老鼠「!有什麼不對?提示:'(應用str(sq-replace(seq」a「)」AA「」肥貓抓老鼠「)''產生''fAAt cAAt cAAught AA rAAt」'。 ?)類型檢查程序可以幫助的情況。 – Thumbnail 2014-09-07 09:20:03

2

這是否適合您?

(defn good-fnc [s sub r] 
    (loop [acc [] 
     s s] 
    (cond 
     (empty? s) (seq acc) 
     (= (take (count sub) s) sub) (recur (apply conj acc r) 
              (drop (count sub) s)) 
     :else (recur (conj acc (first s)) (rest s))))) 
+0

是它,但我感興趣的標準功能(我認爲這是相當基本的操作,所以如果有字符串的東西,應該有一些向量和列表...) – Mark 2014-09-05 17:07:47

+0

Clojure字符串操作大多隻是jvm互操作。一般序列不支持字符串的許多操作。 – noisesmith 2014-09-05 17:29:09

+0

@noisesmith,所以這意味着沒有標準的功能呢? – Mark 2014-09-05 18:00:04

1

我以前的(現已刪除)的答案是不正確的,因爲這不是因爲我首先想到的是瑣碎的,這裏是我的第二次嘗試:

(defn seq-replace 
    [coll sub rep] 
    (letfn [(seq-replace' [coll] 
      (when-let [s (seq coll)] 
       (let [start (take (count sub) s) 
        end (drop (count sub) s)] 
       (if (= start sub) 
        (lazy-cat rep (seq-replace' end)) 
        (cons (first s) (lazy-seq (seq-replace' (rest s))))))))] 
    (seq-replace' coll)))