This is more correct, because conj does not preserve the order correctly.  I
wonder if there is a more idiomatic way to cons things onto the end of the
list.


(defn partition-when [f l]
  (reduce #(if (f %2)
             (concat %1 (vector (vector %2)))
             (concat (butlast %1)
                     (vector (concat (last %1) (vector %2)))))
          [] l))


On Sat, Nov 27, 2010 at 4:18 PM, rob levy <r.p.l...@gmail.com> wrote:

> Something like this?
>
> (defn partition-when [f l]
>   (reduce #(if (f %2)
>              (conj %1 (vector %2))
>              (conj (butlast %1)
>                    (conj (last %1) %2)))
>           [] l))
>
> On Sat, Nov 27, 2010 at 4:15 PM, Ken Wesson <kwess...@gmail.com> wrote:
>
>> On Sat, Nov 27, 2010 at 4:00 PM, rob levy <r.p.l...@gmail.com> wrote:
>> > partition-by does exactly what you need.
>>
>> Not quite.
>>
>> user=> (take 10 (partition-by #(= 0 (rem % 3)) (iterate inc 1)))
>> ((1 2)
>>  (3)
>>  (4 5)
>>  (6)
>>  (7 8)
>>  (9)
>>  (10 11)
>>  (12)
>>  (13 14)
>>  (15))
>>
>> At first it seems you can fix this as follows:
>>
>> user=> (defn questionable-split-when [pred coll]
>>         (let [p (partition-by pred coll)]
>>           (cons (first p) (map #(apply concat %) (partition 2 2 []
>> (rest p))))))
>> #'user/questionable-split-when
>> user=> (take 10 (questionable-split-when #(= 0 (rem % 3)) (iterate inc
>> 1)))
>> ((1 2)
>>  (3 4 5)
>>  (6 7 8)
>>  (9 10 11)
>>  (12 13 14)
>>  (15 16 17)
>>  (18 19 20)
>>  (21 22 23)
>>  (24 25 26)
>>  (27 28 29))
>>
>> So far, so good. But:
>>
>> user=> (questionable-split-when #(= 0 (rem % 3)) [1 2 3 6 7 8 9])
>> ((1 2)
>>  (3 6 7 8)
>>  (9))
>>
>> Whereas:
>>
>> user=> (split-when #(= 0 (rem % 3)) [1 2 3 6 7 8 9])
>> ((1 2)
>>  (3)
>>  (6 7 8)
>>  (9))
>>
>> The latter correctly starts a new partition each time the pred is
>> true; the former fails if the pred is ever true twice in a row.
>>
>> --
>> 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<clojure%2bunsubscr...@googlegroups.com>
>> For more options, visit this group at
>> http://groups.google.com/group/clojure?hl=en
>>
>
>

-- 
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