Scheme searching
last modified November 25, 2026 Guile 3.0
Searching finds an element, or its position, in a collection. A linear search looks at the elements one by one and works on any list or vector. A binary search needs a sorted vector, but halves the remaining range at each step and finds an element among a million in twenty steps. This article writes both, extends binary search to duplicates, ranges, and any order, and uses the same idea to search for the answer to a numeric question. The examples are run with GNU Guile 3.0.7.
Linear search
A linear search compares each element with the value it looks for, from the first to the last. It stops at the first match or at the end of the list.
(define (position x lst)
(let loop ((lst lst) (i 0))
(cond ((null? lst) #f)
((equal? (car lst) x) i)
(else (loop (cdr lst) (+ i 1))))))
(define primes '(2 3 5 7 11 13 17 19 23 29))
(display (position 13 primes))
(newline)
(display (position 4 primes))
(newline)
(display (position "fig" '("plum" "fig" "kiwi")))
(newline)
position walks the list with a named let and
counts the index. It returns the index of the first equal element, or
#f when there is none. Because it compares with
equal?, it finds strings as well as numbers. The built-in
member from the pairs and lists
article does the same search but returns the rest of the list instead of
an index.
$ guile linear.scm 5 #f 1
Searching with a predicate
A search is more useful when it takes a predicate instead of a value. The predicate decides what counts as a match. This section searches a vector, where elements are reached by index.
(use-modules (srfi srfi-1))
(define (search-vector found? vec)
(let loop ((i 0))
(cond ((= i (vector-length vec)) #f)
((found? (vector-ref vec i)) i)
(else (loop (+ i 1))))))
(define (search-all found? vec)
(do ((i (- (vector-length vec) 1) (- i 1))
(hits '() (if (found? (vector-ref vec i)) (cons i hits) hits)))
((< i 0) hits)))
(define levels (vector 3.1 2.8 4.6 5.2 4.9 6.3 5.8 2.2))
(display (search-vector (lambda (x) (> x 5)) levels))
(newline)
(display (search-vector (lambda (x) (> x 10)) levels))
(newline)
(display (search-all (lambda (x) (> x 5)) levels))
(newline)
(define readings (vector->list levels))
(display (find (lambda (x) (> x 5)) readings))
(display " ")
(display (list-index (lambda (x) (> x 5)) readings))
(display " ")
(display (find-tail (lambda (x) (> x 5)) readings))
(newline)
search-vector returns the index of the first element that
satisfies found?. search-all collects the
indexes of all matches; its do loop runs backwards, so
cons builds the list in ascending order. For lists, the
SRFI 1 list library already has these
searches: find returns the matching element,
list-index its index, and find-tail the rest of
the list from the match.
$ guile predicate.scm 3 #f (3 5 6) 5.2 3 (5.2 4.9 6.3 5.8 2.2)
Binary search
In a sorted vector, one comparison with the middle element tells which
half can hold the value. Binary search keeps a range of candidate indexes,
from low to high, and halves it until it finds
the value or the range is empty.
(define (binary-search vec x)
(let loop ((low 0) (high (- (vector-length vec) 1)))
(if (> low high)
#f
(let* ((mid (quotient (+ low high) 2))
(value (vector-ref vec mid)))
(cond ((= value x) mid)
((< value x) (loop (+ mid 1) high))
(else (loop low (- mid 1))))))))
(define primes (vector 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47))
(display (binary-search primes 2))
(display " ")
(display (binary-search primes 23))
(display " ")
(display (binary-search primes 47))
(newline)
(display (binary-search primes 24))
(display " ")
(display (binary-search primes 1))
(display " ")
(display (binary-search primes 50))
(newline)
(display (binary-search (vector) 5))
(newline)
The middle index is the integer average of the bounds. When the middle
value is smaller than x, the value can only be to the right,
so the search continues from mid + 1; when it is larger, the
search continues to the left. When low passes
high, the range is empty and the value is absent. The search
finds the first, a middle, and the last element, and returns
#f for values between, before, and after the elements, and
for an empty vector. On an unsorted vector, binary search gives wrong
answers without any error.
$ guile binary.scm 0 8 14 #f #f #f #f
Counting probes
The cost of a search is the number of elements it looks at, its probes. The program reads the vectors through a procedure that counts the reads and searches vectors of growing size.
(use-modules (ice-9 format))
(define probes 0)
(define (probe vec i)
(set! probes (+ probes 1))
(vector-ref vec i))
(define (linear-search vec x)
(let loop ((i 0))
(cond ((= i (vector-length vec)) #f)
((= (probe vec i) x) i)
(else (loop (+ i 1))))))
(define (binary-search vec x)
(let loop ((low 0) (high (- (vector-length vec) 1)))
(if (> low high)
#f
(let* ((mid (quotient (+ low high) 2))
(value (probe vec mid)))
(cond ((= value x) mid)
((< value x) (loop (+ mid 1) high))
(else (loop low (- mid 1))))))))
(define (count-probes search vec x)
(set! probes 0)
(search vec x)
probes)
(define (even-numbers n)
(list->vector (map (lambda (i) (* 2 i)) (iota n))))
(for-each
(lambda (n)
(let ((vec (even-numbers n)))
(format #t "~9:d linear ~9:d binary ~2d missing ~2d~%"
n
(count-probes linear-search vec (* 2 (- n 1)))
(count-probes binary-search vec (* 2 (- n 1)))
(count-probes binary-search vec 1))))
'(10 100 1000 10000 100000 1000000))
The vectors hold even numbers, so the odd number 1 is missing. The
program searches for the last element, the worst case for the linear
search, and for the missing value. format with
~:d groups the digits, as described in the
number formatting article. The
linear search needs as many probes as there are elements. The binary
search needs about log2(n) probes, at most 20 for a million
elements, whether the value is present or not. Keeping a vector sorted,
as in the sorting article, pays off when it
is searched many times.
$ guile probes.scm
10 linear 10 binary 4 missing 3
100 linear 100 binary 7 missing 7
1,000 linear 1,000 binary 10 missing 10
10,000 linear 10,000 binary 14 missing 13
100,000 linear 100,000 binary 17 missing 17
1,000,000 linear 1,000,000 binary 20 missing 20
Lower and upper bounds
When a vector contains duplicates, binary search returns one of the equal
elements, not necessarily the first. A lower bound search
returns the first index whose element is not smaller than
x; an upper bound search returns the first index
whose element is larger than x. Both always return an index,
which is also where x could be inserted to keep the vector
sorted.
(define (lower-bound vec x)
(let loop ((low 0) (high (vector-length vec)))
(if (= low high)
low
(let ((mid (quotient (+ low high) 2)))
(if (< (vector-ref vec mid) x)
(loop (+ mid 1) high)
(loop low mid))))))
(define (upper-bound vec x)
(let loop ((low 0) (high (vector-length vec)))
(if (= low high)
low
(let ((mid (quotient (+ low high) 2)))
(if (<= (vector-ref vec mid) x)
(loop (+ mid 1) high)
(loop low mid))))))
(define (count-equal vec x)
(- (upper-bound vec x) (lower-bound vec x)))
(define (count-between vec low high)
(- (upper-bound vec high) (lower-bound vec low)))
(define grades (vector 1 1 2 2 2 2 3 3 4 5 5))
(display (list (lower-bound grades 2) (upper-bound grades 2)))
(newline)
(display (list (lower-bound grades 4) (upper-bound grades 4)))
(newline)
(display (map (lambda (g) (count-equal grades g)) '(1 2 3 4 5 6)))
(newline)
(display (count-between grades 2 4))
(newline)
(display (list (lower-bound grades 0) (lower-bound grades 9)))
(newline)
Both searches keep the half-open range from low up to, but
not including, high, and stop when it is empty. They differ
only in the comparison: < moves past the smaller elements,
<= also past the equal ones. The grade 2 occupies indexes
2 to 5, so the bounds are 2 and 6. The difference of the bounds is the
number of equal elements, and the bounds of two values count the elements
in a range: seven grades lie between 2 and 4. A value smaller than all
elements gives index 0, a larger one the length of the vector.
$ guile bounds.scm (2 6) (8 9) (2 4 2 1 2 0) 7 (0 11)
Searching with a comparator
A general binary search takes a comparison procedure, as the sorts in the sorting article do, and a key procedure that extracts the compared value from an element. It goes into a module, as described in the modules article.
(define-module (search)
#:export (lower-bound binary-search))
(define* (lower-bound vec x less? #:key (key (lambda (v) v)))
(let loop ((low 0) (high (vector-length vec)))
(if (= low high)
low
(let ((mid (quotient (+ low high) 2)))
(if (less? (key (vector-ref vec mid)) x)
(loop (+ mid 1) high)
(loop low mid))))))
(define* (binary-search vec x less? #:key (key (lambda (v) v)))
(let ((i (lower-bound vec x less? #:key key)))
(and (< i (vector-length vec))
(not (less? x (key (vector-ref vec i))))
i)))
Both procedures are defined with define* from the
procedures article; the key is a keyword
argument that defaults to the element itself. binary-search
uses the lower bound: the element there is equal to x when
x is not smaller than it. Only less? is needed
to test equality.
(use-modules (search) (srfi srfi-1) (srfi srfi-9))
(define-record-type <airport>
(make-airport code city)
airport?
(code airport-code)
(city airport-city))
(define airports
(vector (make-airport "AMS" "Amsterdam") (make-airport "BTS" "Bratislava")
(make-airport "BUD" "Budapest") (make-airport "KSC" "Kosice")
(make-airport "PRG" "Prague") (make-airport "VIE" "Vienna")))
(define (city-of code)
(let ((i (binary-search airports code string<? #:key airport-code)))
(if i
(airport-city (vector-ref airports i))
"unknown")))
(display (map city-of '("BTS" "VIE" "AMS" "LHR")))
(newline)
(define words (vector "apple" "banana" "cherry" "kiwi" "plum"))
(display (binary-search words "kiwi" string<?))
(display " ")
(display (binary-search words "fig" string<?))
(display " ")
(display (lower-bound words "fig" string<?))
(newline)
(define (insert-at vec i x)
(let ((lst (vector->list vec)))
(list->vector (append (take lst i) (list x) (drop lst i)))))
(display (insert-at words (lower-bound words "fig" string<?) "fig"))
(newline)
(display (binary-search (vector 50 40 30 20 10) 20 >))
(newline)
The airports are records sorted by code.
city-of searches with string<? and
airport-code as the key. The words show that the lower bound
of a missing word is its insertion point, and insert-at
builds a new vector with the word in place. The last search uses
> on a vector in descending order: the comparison must
match the order of the vector. The vector-binary-search
procedure of SRFI 43, shown in the vectors
article, takes a comparison that returns a negative number, zero, or a
positive number instead.
$ guile -L . airports.scm (Bratislava Vienna Amsterdam unknown) 3 #f 3 #(apple banana cherry fig kiwi plum) 3
Searching for an answer
Binary search also works without a vector. When a condition is false for small numbers and true from some number on, binary search finds the first number for which it is true. The same halving finds where a continuous function changes sign; this is called bisection.
(define (first-true ok? low high)
(if (= low high)
low
(let ((mid (quotient (+ low high) 2)))
(if (ok? mid)
(first-true ok? low mid)
(first-true ok? (+ mid 1) high)))))
(define (integer-sqrt n)
(- (first-true (lambda (r) (> (* r r) n)) 0 (+ n 1)) 1))
(display (integer-sqrt 99))
(display " ")
(display (integer-sqrt 100))
(display " ")
(display (integer-sqrt (expt 10 40)))
(newline)
(define (factorial n)
(if (= n 0) 1 (* n (factorial (- n 1)))))
(display (first-true (lambda (n) (> (factorial n) (expt 10 100))) 0 1000))
(newline)
(define (bisect f low high tolerance)
(let ((mid (/ (+ low high) 2.0)))
(cond ((< (- high low) tolerance) mid)
((eq? (negative? (f mid)) (negative? (f low)))
(bisect f mid high tolerance))
(else (bisect f low mid tolerance)))))
(define (cubic x) (- (* x x x) x 2))
(display (bisect cubic 1.0 2.0 1e-10))
(newline)
(display (bisect (lambda (x) (- (cos x) x)) 0.0 1.0 1e-10))
(newline)
first-true searches the range from low to
high for the first number that satisfies ok?,
which must be true at high. The integer square root is one
less than the first number whose square exceeds n; with
exact integers, it is correct even for 1040. Guile also has
exact-integer-sqrt, which the multiple values article shows. The
second search finds that 70 is the smallest number whose factorial
exceeds a googol. bisect keeps an interval in which the
function changes sign and halves it until it is shorter than the
tolerance. It finds the real root of x3 − x − 2 and
the number that equals its own cosine.
$ guile answer.scm 9 10 100000000000000000000 70 1.5213797068281565 0.7390851332165767
Source
SRFI-1 Searching — GNU Guile Reference Manual
In this article we have searched lists and vectors linearly, with values and predicates, written a binary search for sorted vectors, counted the probes of both searches, found lower and upper bounds, made binary search generic with a comparison and a key, and searched for the answers to numeric questions. The sorting article prepares vectors for binary search, and the hash tables article finds values by key without any ordering.
Author
List all Scheme tutorials.