Emacs Lisp: Test Equality

By Xah Lee. Date: . Last updated: .

Emacs lisp has several functions to test equality.

=
Check if numbers are equal. Numbers can be different type. e.g. (= 3 3.0) is true.
;; compare numbers
(= 3 3) ; t
(= 3 3.0) ; t
string-equal
For comparing strings or Symbols.
Can be used to comparing between a string and a symbol.
;; dedicated function for comparing string
(string-equal "abc" "abc") ;  t
(string-equal "abc" "Abc") ;  nil. Case matters

;; can be used to compare string and symbol
(string-equal "abc" 'abc) ;  t
equal
Check datatype and value are same.
This is the most generic and commonly used. Can be used for comparing Symbols, strings, integers, floats, or list.

WARNING: comparing a integer number and floating number doesn't work. (equal 3 3.0) returns nil.

;; test if two values have the same datatype and value.

(equal 3 3) ;  t
(equal 3.0 3.0) ;  t

(equal 3 3.0) ;  nil. Because datatype doesn't match.

;; test equality of lists
(equal '(3 4 5) '(3 4 5))  ;  t
(equal '(3 4 5) '(3 4 "5")) ;  nil

;; test equality of strings
(equal "e" "e") ;  t

;; test equality of symbols
(equal 'abc 'abc) ;  t
eq
Check if is the same object. Good for comparing Symbols or check if two lists are of the “same address”.
;; work on symbols
(eq 'x 'x) ; t

;; work on integer
(eq 2 2) ; t

;; ------------

;; does not work for string
(eq "e" "e") ; nil

;; does not work for float
(eq 2.1 2.1) ; nil

;; does not work on lists having same items
(let ( aa bb )
  (setq aa '(3 4))
  (setq bb '(3 4))
  (eq aa bb))
;; nil

;; work on lists having same address
(let ( aa bb )
  (setq aa '(3 4))
  (setq bb aa)
  (eq aa bb))
;; t
eql
like eq but also return true for two “same” floating numbers with same sign.
(eql 1.1 1.1) ; t
(eql 0.0 -0.0) ; nil

Test Inequality

;; use “not” to invert equality
(not (equal 3 4)) ;  t

Lisp Basics

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Lisp Basics

Basics

Lisp Data Structure

Function

Lisp Symbol

Lisp Misc

Working with Elisp