Question

I am trying to understand the function "substitute" in LISP, but there is something that I don't understand. When I perform this:

(defparameter *mytree* nil)
(push 1 *mytree*)
(substitute '8 '1 *mytree*)

Everything runs ok, the value of mytree is (8).

But, when I perform:

(defparameter *mytree* nil)
(push "A" *mytree*)
(substitute '8 '"A" *mytree*)

Then mytree is ("A") instead of (8) like I expect.

Any idea why this is happening?

Was it helpful?

Solution

You need to use the correct equality checking method by using the :test keyword in substitute.

The signature for substitute is

(substitute newitem olditem sequence &key from-end test test-not start end count key)

Substitute is using eql by default, but that won't work in this scenario

(eql "A" "A") ;; nil
(equal "A" "A") ;; t

This will yield the correct results

(defparameter *mytree* nil)
(push "A" *mytree*)
(substitute 8 "A" *mytree* :test 'equal) ;; note the test, returns (8)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top