Common lisp 在REPL中打印BST?

Common lisp 在REPL中打印BST?,common-lisp,binary-search-tree,Common Lisp,Binary Search Tree,我试图获得一个二叉搜索树的struct print函数,如下所示,以xml风格打印出一个节点(及其子节点,递归)。其想法是,添加适当的缩进应该可以更容易地查看BST的结构 我目前拥有的是: (defstruct (节点::打印功能 (新南部) (格式s“#”(节点elt n)(节点l n)(节点r n()))) 英语教学(无)(无) 这将打印BST,例如: #<5 #<4 #<2 #<1 NIL NIL> #<3 NIL NIL>> NIL>

我试图获得一个二叉搜索树的struct print函数,如下所示,以xml风格打印出一个节点(及其子节点,递归)。其想法是,添加适当的缩进应该可以更容易地查看BST的结构

我目前拥有的是:

(defstruct
(节点::打印功能
(新南部)
(格式s“#”(节点elt n)(节点l n)(节点r n())))
英语教学(无)(无)
这将打印BST,例如:

#<5 #<4 #<2 #<1 NIL NIL> #<3 NIL NIL>> NIL> #<8 #<6 NIL #<7 NIL NIL>> #<9 NIL NIL>>>
#
但是我想要一些更容易可视化树结构的东西

我有这样的想法:

#<5 
 #<4 
  #<2 
   #<1 NIL NIL> 
   #<3 NIL NIL>> NIL> 
 #<8 
  #<6 NIL 
   #<7 NIL NIL>> 
  #<9 NIL NIL>>>
#
假设我的目标是好的,每行的缩进深度必须取决于递归的深度。我不知道如何在上面的
格式中做到这一点

事实上,也许这毕竟不是一个很好的展示方式

如果不是,那么在REPL中打印(当然很小)二叉搜索树的好方法是什么,这样就可以很容易地看到它的结构?(作为帮助算法开发的工具)


谢谢。

您可以使用逻辑块

(defstruct
    (node
      (:constructor bst (elt &optional l r))
      (:print-function
         (lambda (n s d)
           (declare (ignore d))
           (format s
                   "(~s ~@<~s ~_~s ~_~s)~:>"
                   'bst
                   (node-elt n) (node-l n) (node-r n)))))
  elt (l nil) (r nil))
打印结果 计算时,生成的树以可读回的方式打印,以生成等效树

(BST T
     (BST 1 (BST :X NIL NIL) (BST :Y NIL NIL))
     (BST 2 (BST :A NIL NIL) (BST :B NIL NIL)))
替代打印机 您还可以定义一台打印机,它只使用中间列表打印表单。这更易于编写,并且依赖于现有的漂亮打印函数

(defstruct
        (node
          (:constructor bst (elt &optional l r))
          (:print-function
             (lambda (n s d)
               (declare (ignore d))
               (princ (list 'bst
                            (node-elt n)
                            (node-l n)
                            (node-r n))
                      s))))
      elt (l nil) (r nil))
修改打印机的输出
(defstruct
        (node
          (:constructor bst (elt &optional l r))
          (:print-function
             (lambda (n s d)
               (declare (ignore d))
               (princ (list 'bst
                            (node-elt n)
                            (node-l n)
                            (node-r n))
                      s))))
      elt (l nil) (r nil))
(BST T (BST 1 (BST X NIL NIL) (BST Y NIL NIL))
     (BST 2 (BST A NIL NIL) (BST B NIL NIL)))