lisp 中以特定方式显示列表的函数

Function in lisp that displays a list in a specific way

我需要在 lisp 中创建一个函数来显示如下列表:

(a b (c d) (e f g) h) ->
(a
 b
 (c
  d)
 (e
  f 
  g)
 h)

到目前为止,我设法制作了一个显示这样列表的函数。

(defun print1-lista(l)
   (princ pard)
   (do ((lst l (cdr lst)))
       ((null (cdr lst)) (princ (car lst)) (princ par))
     (princ (car lst))
     (terpri)))

   PRINT1-LISTA
   > (print1-lista '(1 (1 2) 3 4))
   {1
   (1 2)
   3
   4}
   }

这是 PLT-Scheme 中漂亮打印的这种方案的快速粗略草图

(define (deep-ppr lst depth)
  (let ((elt (car lst)))
    (if (list? elt)
        (begin
          (printf "~a(~a\n" (make-string depth #\ ) (car elt))
          (deep-ppr (cdr elt) (+ 1 depth)))
        ;; not a list
        (begin
          (printf "~a~a" (make-string depth #\ ) elt)))
    (if (empty? (cdr lst)) (printf ")")
        (begin
          (printf "\n")
          (deep-ppr (cdr lst) depth)))))

由此产生。您可以根据需要更改引入换行符的方案。

sicp.rkt> (deep-pp '(1 (1 2 4) 3 4 5 6 (1 2 3 5) 7) 0)

(1
 (1
  2
  4)
 3
 4
 5
 6
 (1
  2
  3
  5)
 7)

在 Common Lisp 中,您可以通过多种方式自定义打印机。例如,变量 *print-case**print-margin-right* 将控制符号打印的大小写,以及漂亮打印机使用的右边距。因此你可以这样做:

(let ((*print-case* :downcase)
      (*print-right-margin* 2))
  (pprint '(a b (c d) (e f g) h)))

得到这样的输出:

(a
 b
 (c
  d)
 (e
  f
  g)
 h)