Lisp-打印()而不是空列表(null) [英] Lisp - Print out () instead of nil for empty list

查看:212
本文介绍了Lisp-打印()而不是空列表(null)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Lisp程序,它正在处理嵌套列表并删除与传递给函数的元素匹配的元素.我的问题是,如果删除嵌套列表之一中的所有内容,则需要打印出()而不是NIL.

I have a Lisp program that's going through nested list and deleting elements that match the element passed through to the function. My issue is, if everything in one of the nested list is deleted, I need to print out () instead of NIL.

(defun del (x l &optional l0)
  (cond ((null l) (reverse l0))
    ((if (atom x) (eq x (car l)) (remove (car l) x)) (del x (cdr l) l0))
    (T (del x (cdr l) (cons (if (not (atom (car l))) 
                                    (del x (car l)) 
                                    (car l))
                                 l0)))))

(defun _delete(a l)
(format t "~a~%" (del a l)))

(_delete 'nest '(nest (second nest level) (third (nest) level)))

这将返回

((SECOND LEVEL (THIRD NIL LEVEL))

我需要

((SECOND LEVEL (THIRD () LEVEL))

我尝试使用〜:S格式,但是显然不适用于复合结构.我也尝试了替代函数来替换NIL,也没有结果.

I've tried using the ~:S format but that apparently doesn't work with composite structures. I've also tried the substitute function to replace NIL, also with no results.

推荐答案

两种可能的解决方案:

I.您可以使用格式指令~:A~:S

I. You can use the format directives ~:A or ~:S

(format t "~:a" '()) => ()

但是,此指令仅适用于列表的顶级元素,即

However, this directive works only on the top level elements of a list, i.e.

(format t "~:a" '(a b () c))

将不会打印(A B () C)

(A B NIL C)

因此,如果需要,您需要遍历列表,将~:A递归应用于每个元素.

So you need to loop through the list applying the ~:A to each element recursively if it is a cons.

(defun print-parentheses (l)
  (cond ((consp l) (format t "(")
              (do ((x l (cdr x)))
                  ((null x) (format t ")" ))
                (print-parentheses (car x))
                (when (cdr x) (format t " "))))
        (t (format t "~:a" l)) ))


(print-parentheses '(a b (c () d))) => (A B (C () D))

II.为空列表创建一个打印调度功能,并将其添加到漂亮的打印调度表中:

II. Create a print-dispatch function for empty lists and add it to the pretty print dispatch table:

(defun print-null (stream obj)
  (format stream "()") )

(set-pprint-dispatch 'null #'print-null)

(print '(a () b)) => (A () B) 

后者更简单,但是会影响所有环境,而这可能并不是您想要的.

The latter is simpler, but it affects all the environment, which might not be what you want.

这篇关于Lisp-打印()而不是空列表(null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆