Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a sequence by delimiter in clojure?

Tags:

clojure

Say I have a sequence in clojure like

'(1 2 3 6 7 8)

and I want to split it up so that the list splits whenever an element divisible by 3 is encountered, so that the result looks like

'((1 2) (3) (6 7 8))

(EDIT: What I actually need is

[[1 2] [3] [6 7 8]]

, but I'll take the sequence version too : )

What is the best way to do this in clojure?

partition-by is no help:

(partition-by #(= (rem % 3) 0) '(1 2 3 6 7 8))
; => ((1 2) (3 6) (7 8))

split-with is close:

(split-with #(not (= (rem % 3) 0)) '(1 2 3 6 7 8))
; => [(1 2) (3 6 7 8)]
like image 795
djhaskin987 Avatar asked Mar 10 '23 14:03

djhaskin987


1 Answers

Something like this?

(defn partition-with
  [f coll]
  (lazy-seq
    (when-let [s (seq coll)]
      (let [run (cons (first s) (take-while (complement f) (next s)))]
        (cons run (partition-with f (seq (drop (count run) s))))))))

(partition-with #(= (rem % 3) 0) [1 2 3 6 7 8 9 12 13 15 16 17 18])
=> ((1 2) (3) (6 7 8) (9) (12 13) (15 16 17) (18))
like image 59
Derek Troy-West Avatar answered Mar 17 '23 16:03

Derek Troy-West