Setting up a equal function in common lisp using o

2019-03-05 10:55发布

问题:

I've given the assingment to write a function in common lisp to compare two lists to see if they are equal and I have been bared from using the "equal" predicate I can only use "eq" and I seem to come to a wall. I get this error with my code EVAL: variable SETF has no value The following restarts are available: and he code:

(defun check(L1 L2)
  (cond
   ((eq L nil) nil)
   (setq x (first L1))
   (setq y (first L2))
   (setf L1 (rest L1))
   (setf L2 (rest L2))
   (if (eq x y) (check L1 L2))))

(defun b(L1 L2)
  (cond
   ((eq L1 nil) nil)
   (setf x (first L1))
   (setf y (first L2))
   (setf L1 (rest L1))
   (setf L2 (rest L2))
   (if (and (list x) (list y)
           (check(x y))
            (if (eq x y) (b(L1 L2))))))

回答1:

I guess this is what you are looking for:

(defun compare-lists (list1 list2)
  (if (and (not (null list1)) 
           (not (null list2)))
      (let ((a (car list1)) (b (car list2)))
        (cond ((and (listp a) (listp b))
               (and (compare-lists a b)
                    (compare-lists (cdr list1) (cdr list2))))
              (t 
               (and (eq a b)
                    (compare-lists (cdr list1) (cdr list2))))))
      (= (length list1) (length list2))))

Tests:

? (compare-lists '(1 2 3) '(1 2 3))
T
? (compare-lists '(1 2 3) '(1 2 3 4))
NIL
? (compare-lists '(1 2 3) '(1 2 (3)))
NIL
? (compare-lists '(1 2 (3)) '(1 2 (3)))
T
? (compare-lists '(1 2 (a b c r)) '(1 2 (a b c (r))))
NIL
? (compare-lists '(1 2 (a b c (r))) '(1 2 (a b c (r))))
T