liveBook · Manning

Partition-by

As explained in Clojure: The Essential Reference

partition-by is a Clojure function that partitions a sequence whenever successive results of a function differ.

partition-by lazily splits a collection into contiguous subsequences whenever successive elements produce different results from a supplied one-argument function. Unlike partition and partition-all, it chooses boundaries by computed values rather than item counts. section 10.6

Its contract and practical behavior are:

  • Call (partition-by f coll) with a function f and a collection compatible with seq. section 10.6
  • Call (partition-by f) to obtain a transducer instead of immediately partitioning a collection. section 10.6 section 7.2
  • Keep consecutive elements together while f returns the same value; start a new subsequence when that value changes. section 10.6

Group adjacent values by a derived property

(partition-by count (map str [12 11 8 2 100 102 105 1 3])) ;; (("12" "11") ("8" "2") ("100" "102" "105") ("1" "3")) Here, count changes from 2 to 1, then to 3, so each change begins a new partition.

Measure contiguous runs

(map count (partition-by identity temps)) ;; (4 3 3 2 1 1 1 1 4 2) Using identity groups adjacent equal temperatures, while later repetitions after an interruption form new runs.

Listing 10.6. → Lazy processing, Sequence splitting, Subsequence
(partition
  ([n coll])
  ([n step coll])
  ([n step pad coll]))

(partition-all
  ([n])
  ([n coll])
  ([n step coll]))

(partition-by
  ([f])
  ([f coll]))

Browse the available partition-by arities alongside partition and partition-all. section 10.6

How Clojure: The Essential Reference covers it

How deep it goes
Explains the split rule, arities, laziness, transducer form, implementation shape, and an unbounded-input hazard.
Examples
Uses string lengths and temperature readings to demonstrate derived-property grouping and contiguous runs.
What it assumes
Assumes familiarity with functions, collections, sequences, laziness, and transducers.
What you can do after
Apply it via the Clojure function or transducer to group adjacent records by changing classifications.
How it connects
Connects partition-by with partition, partition-all, subsequences, lazy sequences, and transducers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.