liveBook · Manning

Distinct keyword

As explained in Clojure: The Essential Reference

distinct is a Clojure function or transducer that removes repeated items from a collection while preserving the first occurrence of each item.

`distinct` removes repeated values from a collection, retaining each value’s first occurrence. It returns a lazy sequence, so the result follows the input’s order rather than sorting it. Duplicate detection uses Clojure’s equality semantics for both scalar values and collections. section 10.8 section 6.1

Keep the first occurrence

```clojure (distinct [1 2 1 1 3 2 4 1]) ;; (1 2 3 4) ``` Later appearances of `1` and `2` disappear, even when they are separated from their first appearances. section 10.8

Choose the operation that matches the job:

  • `(dedupe [1 2 1 1 3 2 4 1])` returns `(1 2 1 3 2 4 1)`: it removes only contiguous repetitions. section 10.8
  • `distinct?` reports whether its arguments are all different; it returns a boolean rather than a sequence and requires at least one argument. section 10.8
  • `set` also removes duplicates, but its result does not retain the sequence’s order. section 10.8

With no argument, `(distinct)` returns a transducer. It can follow other transformations in `comp`; for example, `(sequence (comp (map range) cat (distinct)) (range 10))` yields `(0 1 2 3 4 5 6 7 8)`. The collection argument may be `nil`, but `distinct` does not accept sets, maps, or transients. Use it when repeated values must be removed across the whole input, not merely when adjacent values match. section 10.8 section 7.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines input and output contracts, exceptions, laziness, and transducer use, then contrasts adjacent-only duplicate removal.
Examples
Shows numeric sequences, deduplicated votes grouped by user, and a composed transducer over generated ranges.
What you can do after
Apply it via Clojure’s distinct or its transducer form to retain the first occurrence of each value.
How it connects
Connects duplicate removal to Clojure equality, dedupe, distinct?, sets, and transducers.

Also explained in

Compare how 4 books explain distinct keyword →

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.