Here are a couple of implementations of a function I'm calling
'partition-when'.  I feel like there should be a simpler way than
either of these. If you have one, I'd love to see it.

(defn partition-when                        ;;version 1
  "Partition a sequence into subsequences; begin a new
   subseq whenever the predicate f? returns true.
   Example: (partition-when even? [ 1 2 3 7 5 4 1]) returns [[1] [2 3
7 5] [4 1]]."
  [f? ys]
  (let [xs (vec ys)
        indices (positions f? xs)         ;; uses
clojure.contrib.seq-utils/positions
        n (count xs)]
    (->> (concat [0] indices [n])
         (distinct)                                 ;; handle possible
repeated leading zero
         (partition 2 1)
         (map #(apply (partial subvec xs) %)))))

(defn partition-when                        ;; version 2
  [f? xs]
  (when (seq xs)
    (loop [ys    (rest xs)
           work  [(first xs)]
           accum []]
      (if (empty? ys)
        (conj accum work)
        (let [y (first ys)]
          (if (f? y)
            (recur (rest ys) [y] (conj accum work))
            (recur (rest ys) (conj work y) accum )))))))

Speed is no big deal for me; the sequences I'm handling are short, say
about length100. BTW, one of these is considerably faster than the
other for longish sequences. Can you guess which?

What I'm looking for is a natural, conceptually clean approach.

Thanks,
David

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to