【发布时间】:2018-01-22 23:04:03
【问题描述】:
我有以下基本类和方法:
(defgeneric connect-edge (edge))
(defclass Node ()
((forward-edges :initform nil)
(backward-edges :initform nil)
(value :initform 0.0)))
(defclass Edge ()
((value :initform 0.0)
(nodes :initform nil)))
(defmethod connect-edge ((edge Edge))
;; does nothing important. Simplified to cause the problem
(slot-value (car (slot-value edge 'nodes)) 'forward-edges))
我将方法简化到足以给我一个错误。基本上它在这一点上没有做任何有用的事情,但足以证明问题。
设置:
Edge 类具有nodes,它是Node 对象的列表。 Node 类具有Edge 对象的列表。
意图:
读取/写入封装在Edge 对象(节点列表)中的Node 对象中的forward-edges 和backward-edges
问题/疑问:
通过按预期返回 nil 来“工作”:
(defparameter *edge* (make-instance 'Edge))
(setf (slot-value *edge* 'nodes) (list (make-instance 'Node) (make-instance 'Node)))
(connect-edge *edge*)
这段代码给了我下面的错误,为什么?
(connect-edge (make-instance 'Edge))
There is no applicable method for the generic function
#<STANDARD-GENERIC-FUNCTION (SB-PCL::SLOT-ACCESSOR :GLOBAL
COMMON-LISP-USER::FORWARD-EDGES
SB-PCL::READER) (1)>
when called with arguments
(NIL).
另外,如果我这样做,我会收到以下错误,我想我明白为什么:没有定义需要 nil 的通用函数:
(connect-edge nil)
There is no applicable method for the generic function
#<STANDARD-GENERIC-FUNCTION COMMON-LISP-USER::CONNECT-EDGE (1)>
when called with arguments
(NIL).
[Condition of type SIMPLE-ERROR]
我为什么要这么做?
我有以下代码导致(可能是由于不同的原因)类似的错误:
(defun make-classic (net)
(loop
for this-layer in net
for next-layer in (cdr net)
do
(loop
for this-node in this-layer
do
(loop
for next-node in next-layer
do
(let ((edge (make-instance 'Edge)))
(setf (slot-value edge 'nodes) '(this-node next-node))
(format t "Type of edge is ~a~%" (type-of edge))
;; Error is here
(connect-edge edge))))))
我不确定错误是否是由于传递了一个作用域变量,所以我最终尝试传递一个(make-instance 'Edge) 来导致错误。
【问题讨论】:
-
这在很大程度上是不相关的,但通常认为在低级方法之外使用
slot-value是不好的形式(就像在 Java 中使用公共字段是不好的形式一样)。相反,您可以在defclass期间使用:reader或:accessor参数。除非将阅读器设置为区分大小写(有些人使用诸如<class>之类的排版约定作为类名),否则对符号使用混合大小写通常也是不习惯的
标签: common-lisp clos