我需要在通用方法中返回矩形的坐标列表。坐标是类“购物车”实例。
我尝试用 make-instance 返回它
(defclass line ()
((start :initarg :start :accessor line-start)
(end :initarg :end :accessor line-end)))
(defmethod print-object ((lin line) stream)
(format stream "[LINE ~s ~s]"
(line-start lin) (line-end lin)))
(defclass cart ()
((x :initarg :x :reader cart-x)
(y :initarg :y :reader cart-y)))
(defmethod print-object ((c cart) stream)
(format stream "[CART x ~d y ~d]"
(cart-x c) (cart-y c)))
(setq lin (make-instance 'line
:start (make-instance 'cart :x 4 :y 3)
:end (make-instance 'cart :x 7 :y 5)))
(defgeneric containing-rect (shape))
(defmethod containing-rect ((l line))
(let ((x1 (cart-x (line-start l)))
(y1 (cart-y (line-start l)))
(x2 (cart-x (line-end l)))
(y2 (cart-y (line-end l))))
(cond ((= x1 x2)
'((make-instance 'cart :x (1- x1) :y y1)
(make-instance 'cart :x (1+ x1) :y y1)
(make-instance 'cart :x (1- x2) :y y2)
(make-instance 'cart :x (1+ x2) :y y2)))
((= y1 y2)
'((make-instance 'cart :x x1 :y (1- y1))
(make-instance 'cart :x x1 :y (1+ y1))
(make-instance 'cart :x x2 :y (1- y2))
(make-instance 'cart :x x2 :y (1+ y2))))
(t
(rect '((make-instance 'cart :x x1 :y y1)
(make-instance 'cart :x x1 :y y2)
(make-instance 'cart :x x2 :y y2)
(make-instance 'cart :x x2 :y y1)))))))
(print (containing-rect lin))
我想 make-instance
应该为某物分配一个实例
所以我得到了错误的结果
((MAKE-INSTANCE 'CART :X X1 :Y Y1) (MAKE-INSTANCE 'CART :X X1 :Y Y2)
(MAKE-INSTANCE 'CART :X X2 :Y Y2) (MAKE-INSTANCE 'CART :X X2 :Y Y1))
但我需要这样的输出
([CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3] [CART x 4 y 3])
最佳答案
如果您引用
某些东西,它不会被评估。
这个:
'((make-instance 'cart :x (1- x1) :y y1)
(make-instance 'cart :x (1+ x1) :y y1)
(make-instance 'cart :x (1- x2) :y y2)
(make-instance 'cart :x (1+ x2) :y y2))
是一个包含四个文字列表的文字列表,每个列表都以符号MAKE-INSTANCE
开头,然后有一个列表(QUOTE CART)
等。这正是您看到的结果。
您似乎想实际评估一下。最简单的事情就是这样做并列一个 list :
(list (make-instance 'cart :x (1- x1) :y y1)
(make-instance 'cart :x (1+ x1) :y y1)
(make-instance 'cart :x (1- x2) :y y2)
(make-instance 'cart :x (1+ x2) :y y2))
这与引用某物有根本不同。
关于common-lisp - 从泛型方法返回实例列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56394626/