• clojure
• java

# 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))```

### 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."
: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

#### 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"
```