Setting up a equal function in common lisp using only “eq”

喜欢而已 提交于 2019-12-31 05:42:05

问题


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


来源:https://stackoverflow.com/questions/4427321/setting-up-a-equal-function-in-common-lisp-using-only-eq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!