liveBook · Manning

Subseq

As explained in Clojure: The Essential Reference

subseq is a Clojure function that returns a sequence of elements within specified bounds from a sorted collection.

subseq returns a forward sequence of elements selected from a sorted collection by one bound or by a lower and upper bound. It works with sorted-set and sorted-map values, whose keys or elements must be comparable with the supplied keys. section 9.1.3

Use either arity to express a range:

  • Three arguments: (subseq sc test key) selects elements above, below, or inclusively at key, according to test. section 9.1.3
  • Supported comparisons are <, <=, >, and >=; omitting one bound lets the collection's sequence boundary provide it implicitly. section 9.1.3
  • A non-sorted collection or an incomparable key causes ClassCastException. section 9.1.3

Selecting a range

(subseq (apply sorted-set (range 10)) > 2 < 8) ;; (3 4 5 6 7) For a sorted-map, subseq returns map entries rather than bare keys. Use rsubseq when the same bound search should return results in reverse order. section 9.1.3

Prefix completion

(defn complete [w dict] (take 4 (subseq dict >= w))) A dictionary stored in a sorted-set can return the first four words at or after a typed prefix, making subseq useful for simple auto-completion.

How Clojure: The Essential Reference covers it

How deep it goes
Defines arities, comparators, bounds, output order, supported collections, and comparison errors, with concise examples.
Examples
Uses numeric ranges, sorted-map entry searches, dictionary auto-completion, and comparisons with linear sorted-sequence scanning.
What it assumes
Assumes familiarity with Clojure sequences and sorted-set or sorted-map values; teaches bounds and comparators explicitly.
What you can do after
Apply via Clojure's subseq function to select bounded ranges or locate nearest matching elements in sorted collections.
How it connects
Connects sorted collections, sorted-set, sorted-map, sequences, and rsubseq.

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.