liveBook · Manning

Linear search

As explained in Clojure: The Essential Reference

A linear search examines collection elements sequentially until a matching element is found or the collection is exhausted.

Linear search examines collection elements sequentially until a match is found or the collection is exhausted. In Clojure, use explicit scanning functions rather than treating contains? on vectors as an element search. section 8.2.3

Scanning a sequential collection

(some #{:a} [:a :b :c]) ;; :a (some #(= nil %) [:a nil :c]) ;; true some accepts a predicate and returns the matching truthy result; an equality predicate allows searching for nil. section 8.2.3

Choose the operation according to the collection and the question being asked:

  • Do not use (contains? [1 2 3 4] 4) to find an element; on vectors, contains? checks whether an index exists, so this returns false. section 8.2.3
  • Use .contains for supported Java collection types or strings when direct inclusion or substring searching is the intended operation. section 8.2.3
(.contains [:a :b :c :d] :a) ; #1
;; true

(.contains {:a 1} :a) ; #2
;; IllegalArgumentException No matching method found

(.contains "somelongstring" "long") ; #3
;; true

Compare direct inclusion on a vector and substring searching on a string with the unsupported map case. section 8.2.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines sequential scanning and contrasts some, .contains, and contains? without developing implementation internals.
Examples
Uses some on a vector, an equality predicate for nil, vector index checks, and Java .contains calls.
What it assumes
Assumes familiarity with Clojure collections and predicates while clarifying vector keys, set predicates, and nil-search behavior.
What you can do after
Apply it via some or .contains when selecting an explicit element or substring scan.
How it connects
Connects linear search with contains?, some, predicates, sets, vectors, sequential collections, and Java interop.

Also explained in

Compare how 5 books explain linear search →

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.