我在 Lisp 中定义了一个非常简单的数据结构:
;;Data structure for a person
(defstruct person
(name nil)
(age 0)
(siblings nil :type list)) ;; Siblings is a list of person objects
然后我开始实例化一些人物对象:
(setf person-a (make-person :name 'Tim :age 23))
(setf person-b (make-person :name 'Sally :age 21))
(setf person-c (make-person :name 'Louis :age 24))
然后我将 sibling 联系起来(假设他们都是彼此的 sibling ):
(setf (person-siblings person-a) (list person-b person-c))
(setf (person-siblings person-b) (list person-a person-c))
(setf (person-siblings person-c) (list person-b person-a))
然后我怎样才能打印关于我已经实例化和修改的对象的信息?我已经研究了关于打印对象和打印功能的 defstruct 选项,但我无法弄清楚如何正确打印我的对象。使用类似的东西:
(print person-a)
将我的 ACL 解释器发送到无限循环中。
最佳答案
Common lisp 有一个控制递归结构打印的变量:*print-circle*
.在您的 Lisp 中,默认情况下它可能为 false (nil
)(因为它在 SBCL 和 clisp 中 - 我不熟悉 ACL),这可能导致无限循环。如果你将它设置为 t
,你的结构应该打印:
(setf *print-circle* t)
我使用以下文件对此进行了测试:
(defstruct person
(name nil)
(age 0)
(siblings nil :type list))
(setf person-a (make-person :name 'Tim :age 23))
(setf person-b (make-person :name 'Sally :age 21))
(setf person-c (make-person :name 'Louis :age 24))
(setf (person-siblings person-a) (list person-b person-c))
(setf (person-siblings person-b) (list person-a person-c))
(setf (person-siblings person-c) (list person-a person-b))
(setf *print-circle* t)
(format t "~a~&" person-a)
(format t "~a~&" person-b)
(format t "~a~&" person-c)
(print person-a)
(print person-b)
(print person-c)
这是运行该代码的记录:
> sbcl
This is SBCL 1.0.55, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
* (load "defstruct.lisp")
#1=#S(PERSON
:NAME TIM
:AGE 23
:SIBLINGS (#2=#S(PERSON
:NAME SALLY
:AGE 21
:SIBLINGS (#1#
#3=#S(PERSON
:NAME LOUIS
:AGE 24
:SIBLINGS (#1# #2#))))
#3#))
#1=#S(PERSON
:NAME SALLY
:AGE 21
:SIBLINGS (#2=#S(PERSON
:NAME TIM
:AGE 23
:SIBLINGS (#1#
#3=#S(PERSON
:NAME LOUIS
:AGE 24
:SIBLINGS (#2# #1#))))
#3#))
#1=#S(PERSON
:NAME LOUIS
:AGE 24
:SIBLINGS (#2=#S(PERSON
:NAME TIM
:AGE 23
:SIBLINGS (#3=#S(PERSON
:NAME SALLY
:AGE 21
:SIBLINGS (#2# #1#))
#1#))
#3#))
#1=#S(PERSON
:NAME TIM
:AGE 23
:SIBLINGS (#2=#S(PERSON
:NAME SALLY
:AGE 21
:SIBLINGS (#1#
#3=#S(PERSON
:NAME LOUIS
:AGE 24
:SIBLINGS (#1# #2#))))
#3#))
#1=#S(PERSON
:NAME SALLY
:AGE 21
:SIBLINGS (#2=#S(PERSON
:NAME TIM
:AGE 23
:SIBLINGS (#1#
#3=#S(PERSON
:NAME LOUIS
:AGE 24
:SIBLINGS (#2# #1#))))
#3#))
#1=#S(PERSON
:NAME LOUIS
:AGE 24
:SIBLINGS (#2=#S(PERSON
:NAME TIM
:AGE 23
:SIBLINGS (#3=#S(PERSON
:NAME SALLY
:AGE 21
:SIBLINGS (#2# #1#))
#1#))
#3#))
T
* (sb-ext:quit)
如果我离开 *print-circle*
nil
,那么我会得到一个堆栈溢出错误(SB-KERNEL::CONTROL-STACK-EXHAUSTED
在 sbcl 中)。
HTH,
凯尔
关于lisp - 在 Lisp 中打印 defstruct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9343287/