Skip to content

Commit

Permalink
equality: CLOS example, add to index
Browse files Browse the repository at this point in the history
  • Loading branch information
vindarel committed Aug 23, 2024
1 parent a1905c5 commit 1018185
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
38 changes: 36 additions & 2 deletions equality.md
Original file line number Diff line number Diff line change
Expand Up @@ -325,15 +325,49 @@ Trees (lists of lists) TREE-EQUAL (with appropriate :TEST argument)

## How to compare your own objects AKA built-in functions are not object-oriented

In short: use `eq` to check they are two identical objects.
Use `eq` to check that two objects are identical, that they are the same object in memory

If you want to compare your own objects with a logic of your own (for
example, two "person" objects will be considered equal if they have
the same name and surname), you can't specialize a built-in function
for this. Use your own `person=` or similar function, or use a library (see our links below).

While this can be seen as a limitation, not using generic functions
has the advantage to be (much) faster.
has the advantage of being (much) faster.

As an example, let's consider the `person` class from the CLOS tutorial:

```lisp
(defclass person ()
((name
:initarg :name
:accessor name)))
```

Let's create two person objects, they have the same name but are two different objects:

```lisp
(defparameter *p1* (make-instance 'person :name "me"))
(defparameter *p2-same-name* (make-instance 'person :name "me"))
```

Use `eq` to compare two objects:

~~~lisp
(eq *p1* *p1*) ;; => T
(eq *p1* *p2-same-name*) ;; => NIL
~~~

We use our own `person=` method to compare different objects and decide when they are equal:

~~~lisp
(defmethod person= (p1 p2)
(string= (name p1) (name p2)))
(person= *p1* *p2-same-name*) ;; => T
~~~

If you really want to use `=` or `equal`, use a library, see below.


## Credits
Expand Down
1 change: 1 addition & 0 deletions index.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ The CL Cookbook aims to tackle all sort of topics, for the beginner as for the m
* [Strings](strings.html)
+ [Regular Expressions](regexp.html)
* [Numbers](numbers.html)
* NEW! ⭐ [Equality](equality.html)
* [Loops, iteration, mapping](iteration.html)
* [Multidimensional Arrays](arrays.html)
* [Dates and Times](dates_and_times.html)
Expand Down

0 comments on commit 1018185

Please sign in to comment.