ELisp: Equality Test

By Xah Lee. Date: . Last updated: .

Emacs lisp has several functions to test equality.

=
Check if numbers are equal.

Numbers can be a integer and a float.

(= 3 3)
;; t

(= 3.8 3.8)
;; t

;; can compare between int and float
(= 3 3.0)
;; t
;; warning: float problems
(= 3 3.0000000000000001)
;; t
(= 3 3.000000000000001)
;; nil
;; not equal
(/= 3 4) ; t
string-equal
For comparing
  • Two Strings
  • Two Symbols
  • A string and a symbol
;; dedicated function for comparing string
(string-equal "abc" "abc") ;  t

;; string case matters
(string-equal "abc" "Abc") ;  nil

;; can be used to compare two symbols
(string-equal 'abc 'abc) ;  t

;; 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

  • Two Symbols
  • Two Strings
  • Two Integers
  • Two Floats
  • Two List's contents

🛑 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
  • Two Integers
  • Two Symbols
  • Check if two sequences 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
char-equal

For character (integer) comparison only, but dependent on a Buffer Local Variable that controls case sensitivity. [see ELisp: Character Type]

Test Inequality

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

Emacs Lisp Boolean