为什么交联的 defstructs 会导致堆栈溢出?
Why do crosslinked defstructs cause stack overflows?
在摆弄图表时,我遇到了一个我不太理解的奇怪错误。下面的代码重现了这个问题。
;; Define struct to store a node with links to other nodes.
(defstruct node properties links)
;; Make two nodes
(setf a (make-node :properties '(:name a))
b (make-node :properties '(:name b)))
;; Create link from b to a. This works fine...
(push b (node-links a))
;; ... but this crosslink makes lisp chase its own tail for a while and then crash with a stack overflow.
(push a (node-links b))
我用 SBCL 和 Clozure 得到了相同的结果。将 *print-length*
设置为可管理的值无效。
所以我的问题是:为什么这段代码没有创建与循环列表相同类型的无限打印循环(即,没有堆栈溢出并且可以使用 Ctrl-C 停止)。欢迎任何意见。
谢谢,
保罗
*print-length*
控制列表中元素的数量。您正在寻找 *print-level*
。这对我来说很好。
(let ((*print-level* 3))
(format t "~W~%" a))
;; Output: #S(NODE :PROPERTIES (:NAME A)
;; :LINKS (#S(NODE :PROPERTIES # :LINKS #)))
或者,您可以使用 *print-circle*
来检测循环并以更好的方式打印它们。
(let ((*print-circle* t))
(format t "~W~%" a))
;; Output: #1=#S(NODE :PROPERTIES (:NAME A)
;; :LINKS (#S(NODE :PROPERTIES (:NAME B) :LINKS (#1#))))
在这里,它实际上检测到循环并打印 #1#
,对 #1=
的引用以表明它是同一个对象。
在摆弄图表时,我遇到了一个我不太理解的奇怪错误。下面的代码重现了这个问题。
;; Define struct to store a node with links to other nodes.
(defstruct node properties links)
;; Make two nodes
(setf a (make-node :properties '(:name a))
b (make-node :properties '(:name b)))
;; Create link from b to a. This works fine...
(push b (node-links a))
;; ... but this crosslink makes lisp chase its own tail for a while and then crash with a stack overflow.
(push a (node-links b))
我用 SBCL 和 Clozure 得到了相同的结果。将 *print-length*
设置为可管理的值无效。
所以我的问题是:为什么这段代码没有创建与循环列表相同类型的无限打印循环(即,没有堆栈溢出并且可以使用 Ctrl-C 停止)。欢迎任何意见。
谢谢, 保罗
*print-length*
控制列表中元素的数量。您正在寻找 *print-level*
。这对我来说很好。
(let ((*print-level* 3))
(format t "~W~%" a))
;; Output: #S(NODE :PROPERTIES (:NAME A)
;; :LINKS (#S(NODE :PROPERTIES # :LINKS #)))
或者,您可以使用 *print-circle*
来检测循环并以更好的方式打印它们。
(let ((*print-circle* t))
(format t "~W~%" a))
;; Output: #1=#S(NODE :PROPERTIES (:NAME A)
;; :LINKS (#S(NODE :PROPERTIES (:NAME B) :LINKS (#1#))))
在这里,它实际上检测到循环并打印 #1#
,对 #1=
的引用以表明它是同一个对象。