Comparing Values

Use equal? to compare contents, eq? to check for the same object, and = to compare numbers.

Use equal? to compare the contents of lists or vectors, and eq? to ask whether two values are the same object. Use = for numbers. Matching contents is called equality, and being the same object is called object identity.

Compare two lists

Paste this example into the playground and run it.

LISPEX
(define xs (list 1 2))
(define same xs)
(define other (list 1 2))
(list (equal? xs other) (eq? xs other) (eq? xs same))

Result

OUTPUT
(#t #f #t)

xs and other refer to separately created lists. Their elements match, so equal? returns #t. They are different objects, so eq? returns #f.

same refers to the list already stored in xs. Their eq? comparison returns #t. Object identity means referring to that same object.

Compare numbers

LISPEX
(list (= 2 2.0) (eqv? 2 2.0) (equal? (list 1 2) (list 1 2)))

Result

OUTPUT
(#t #f #t)

= treats exact 2 and inexact 2.0 as the same mathematical number. eqv? distinguishes exact from inexact numbers, so its result is #f.

equal? also distinguishes exact from inexact numbers, including inside lists. The last comparison returns #t because both lists contain the same exact integers.

Choose a comparison

A predicate is a procedure that answers a question with #t or #f.

PredicateWhat it compares
=mathematical values of numbers; other types cause an error
eq? / eqv?atoms by value, preserving numeric exactness; aggregate values by object identity
equal?contents of pairs, vectors, bytevectors, and strings; nested values are compared too
== / !=equal? / the opposite of equal?

Atoms here are numbers, characters, booleans, symbols, and the empty list. eq? and eqv? produce the same result in the current language profile.

equal? detects cycles while comparing nested values, so comparison finishes even when a structure refers back to itself. Procedures are compared by object identity, including under equal?. Their bodies are not compared.

Data and aggregate types helps you choose a value. List and aggregate procedures shows how to create values and change a vector's contents.