我正在 Common Lisp (CLISP) 中实现进化算法,但我遇到了问题。
我有一个类似树的类:
(defclass node ()
((item :initarg :item :initform nil :accessor item)
(children :initarg :children :initform nil :accessor children)
(number-of-descendants :initarg :descs :initform nil :accessor descs)))
还有一些方法:
(defmethod copy-node ((n node))
(make-instance
'node
:item (item n)
:descs (descs n)
:children (mapcar #'copy-node (children n))))
(defmethod get-subtree ((n node) nr)
(gsth (children n) nr))
(defmethod (setf get-subtree) ((val node) (n node) nr)
(setf (gsth (children n) nr) val))
(defmethod get-random-subtree ((n node))
(gsth (children n) (random (descs n))))
(defmethod (setf get-random-subtree) ((val node) (n node))
(setf (get-subtree n (random (descs n))) val))
(defun gsth (lst nr)
(let ((candidate (car lst)))
(cond
((zerop nr) candidate)
((<= nr (descs candidate)) (gsth (children candidate) (1- nr)))
(t (gsth (cdr lst) (- nr (descs candidate) 1))))))
(defun (setf gsth) (val lst nr)
(let ((candidate (car lst)))
(cond
((zerop nr) (setf (car lst) val))
((<= nr (descs candidate))
(setf (gsth (children candidate) (1- nr)) val))
(t (setf (gsth (cdr lst) (- nr (descs candidate) 1)) val)))
val))
我想要做的是从人口中交换两个随机树的两个随机子树。但是当我做这样的事情时:
(defun stdx (population)
(let ((n (length population))
(npop))
(do ((done 0 (+ done 2)))
((>= done n) npop)
(push (stdx2 (copy-node (random-el population))
(copy-node (random-el population)))
npop))))
(defun stdx2 (father mother)
;; swap subtrees
(rotatef (get-random-subtree father)
(get-random-subtree mother))
(check-for-cycles father)
(check-for-cycles mother))
有时会检测到一个循环,这显然不应该发生。
Check-for-cycles 没问题,我也用 (trace) 检测到了循环。我一直在更新后代的数量。
我想(setf get-subtree)有问题。我是 LISP 的新手,我对 setf 扩展不是很好。请帮我。