Google News
logo
Lisp - Interview Questions
Describe the difference between "eq" and "equal" in Lisp.
In Lisp, the functions `eq` and `equal` are used for equality comparison, but they differ in their behavior and the type of equality they test for. Here's an explanation of the difference between `eq` and `equal`:

1. `eq`:
   * The `eq` function is a primitive comparison function in Lisp that tests for object identity.
   * It returns `t` if the two arguments refer to the same memory location or object.
   * `eq` compares the actual memory addresses of the objects being compared.
   * It is typically used to compare symbols or to check whether two objects are identical, referring to the same underlying object in memory.
   * `eq` is a more efficient comparison operation compared to `equal`, as it avoids traversing the objects' contents.

2. `equal`:
   * The `equal` function is a general-purpose comparison function in Lisp that tests for structural equality.
   * It recursively compares the contents of the objects being compared, rather than comparing memory addresses.
   * `equal` considers objects equal if their contents are the same, even if they are not the same memory objects.
   * `equal` can be used to compare atoms (symbols, numbers, strings) and complex data structures such as lists, arrays, and nested structures.
   * It provides a deep comparison, recursively checking the equality of all elements within the data structures being compared.
   * `equal` is a more flexible and inclusive equality test, suitable for most cases when comparing Lisp data.
Here are some examples to illustrate the difference :
(let ((x '(1 2 3))
      (y '(1 2 3)))
  (eq x y))     ; Returns NIL, as x and y are different objects

(let ((x '(1 2 3))
      (y x))
  (eq x y))     ; Returns T, as x and y point to the same object

(let ((x '(1 2 3))
      (y '(1 2 3)))
  (equal x y))  ; Returns T, as the contents of x and y are the same

(let ((x '(1 2 3))
      (y '(1 2 3)))
  (eq (car x) (car y)))    ; Returns T, as the first elements are symbols '1' in both x and y

(let ((x '(1 2 3))
      (y '(1 2 3)))
  (equal (car x) (car y))) ; Returns T, as the first elements are atoms with the same value '1' in both x and y​

The`eq` tests for object identity by comparing memory addresses, while `equal` tests for structural equality by comparing the contents of objects. The choice between `eq` and `equal` depends on the specific comparison needed in a given context.
Advertisement