Applies f to each value in coll, splitting it each time f returns
a new value. Returns a lazy seq of partitions.
;; (this is part of a solution from 4clojure.com/problem 30) user=> (partition-by identity "Leeeeeerrroyyy") ((\L) (\e \e \e \e \e \e) (\r \r \r) (\o) (\y \y \y))
(defn partition-by
"Applies f to each value in coll, splitting it each time f returns
a new value. Returns a lazy seq of partitions."
{:added "1.2"
:static true}
[f coll]
(lazy-seq
(when-let [s (seq coll)]
(let [fst (first s)
fv (f fst)
run (cons fst (take-while #(= fv (f %)) (next s)))]
(cons run (partition-by f (seq (drop (count run) s))))))))
Comments top
1 comment(s) for partition-by.
It's worth mentioning that
(partition-by identity …)is equivalent to theData.List.groupfunction in Haskell:Which proves to be an interesting idiom:
user=> (apply str (for [ch (group "fffffffuuuuuuuuuuuu")] (str (first ch) (count ch)))) ⇒ "f7u12"user=> (apply str (for [ch (group "fffffffuuuuuuuuuuuu")] (str (first ch) (count ch)))) ⇒ "f7u12"