1.3.0 permalink Arrow_down_16x16

partition-by

clojure.core

  • (partition-by f coll)
Applies f to each value in coll, splitting it each time f returns
a new value. Returns a lazy seq of partitions.

3 Examples top

  • user=> (partition-by #(= 3 %) [1 2 3 4 5])
    ((1 2) (3) (4 5))
  • user=> (partition-by odd? [1 1 1 2 2 3 3])
    ((1 1 1) (2 2) (3 3))
    
    user=> (partition-by even? [1 1 1 2 2 3 3])
    ((1 1 1) (2 2) (3 3))
    
  • ;; (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))
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:6242 top

(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))))))))
Vars in clojure.core/partition-by:
Used in 0 other vars

Comments top

1 comment(s) for partition-by.

It's worth mentioning that (partition-by identity …) is equivalent to the Data.List.group function in Haskell:

 
(defn group [coll]
  (partition-by identity coll))

Which proves to be an interesting idiom:

user=> (apply str 
         (for [ch (group "fffffffuuuuuuuuuuuu")] 
           (str (first ch) (count ch))))
⇒ "f7u12"
Log in to add a comment.