Demo entry 1466575

Clojure partition-when transducer


Submitted by anonymous on Mar 05, 2015 at 18:08
Language: Clojure. Code size: 1.0 kB.


(defn partition-when
  (fn [rf]
    (let [a (java.util.ArrayList.)
          fval (volatile! false)]
        ([] (rf))
           (let [result (if (.isEmpty a)
                          (let [v (vec (.toArray a))]
                            ;;clear first!
                            (.clear a)
                            (unreduced (rf result v))))]
             (rf result)))
        ([result input]
            (if-not (and (f input)  @fval)
                 (vreset! fval true)
                 (.add a input)
               (let [v (vec (.toArray a))]
                 (.clear a)
                 (let [ret (rf result v)]
                   (when-not (reduced? ret)
                     (.add a input))

(into [] (partition-when
          #(.startsWith % ">>"))
          ["1d" "33" ">> 1" ">> 2" "22" ">> 3"])

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).