On Thu, Sep 16, 2010 at 10:45 PM, Chouser <[email protected]> wrote:
> On Fri, Sep 10, 2010 at 4:26 PM, Matt Smith <[email protected]> wrote:
> > problem: convert a collection [1 2 0 1 2 3 0 1 2 3 0 0 1 2] into
> > partitions like:
> > ((1 2) (0 1 2 3) (0 1 2 3) (0) (0 1 2))
> > In this case, start each partition on a 0.
>
> Iteration at a rate other than once per input seq item suggests iterate:
>
> (defn partition-starting-every [f coll]
> (->> [nil coll]
> (iterate (fn [[p [x :as s1]]]
> (let [[n s2] (split-with (complement f) (next s1))]
> (when (seq s1)
> [(cons x n) s2]))))
> (map first)
> next
> (take-while identity)))
>
> Ugh. Well, maybe partition-by can be used after all:
>
> (defn partition-starting-every [f coll]
> (let [pb (partition-by #(and (f %) (Object.)) coll)]
> (->> (map (fn [[a :as as] [b :as bs]]
> (cond
> (nil? as) (when-not (f b) bs)
> (and (f a) (f b)) as
> (f a) (concat as bs)))
> (cons nil pb) pb)
> (remove nil?))))
>
>
Nice trick that your #(and (f %) (Object.)) however #(when (f %) (Object.))
would be better because it would produce only one false value (nil) instead
of two (nil and false).
For comprehensiveness, let's not forget reductions :-)
(defn partition-starting-every
"Partition the sequence starting each partition when the f is true."
[f coll]
(map #(map first %)
(partition-by second
(map vector coll
(rest (reductions #(if (f %2) (inc %1) %1) 0 coll))))))
Christophe
--
Professional: http://cgrand.net/ (fr)
On Clojure: http://clj-me.cgrand.net/ (en)
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en