我在 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))
然后我将兄弟姐妹联系起来(假设他们都是彼此的兄弟姐妹):
(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,
Kyle
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)