列表的 lisp Cons 单元图

标签 lisp common-lisp

这是我的尝试代码。

(defun f (lst)
  (cond ((null lst) nil)
        ((listp (first lst))
         nil
         (f (car lst)))
        (t (cons (first lst)
                 (list (f (cdr lst)))))))
(f '(a (b) c))
==> (A (B NIL))

我的目标是 (f '(a (b) c)) 应该返回 (a . ((b . nil) . (c . nil))) .

或者 (f '(a b)) 应该返回 (a . (b . nil))

这个意思是过程cons cell。

我该如何解决?

我想知道的另一件事是过程符号。

为了处理符号,我使用 try (format t ". ") 并递归地打印列表,

但进展并不顺利。

我应该从哪里开始修改?

最佳答案

你说的

返回 (a . ((b . nil) . (c . nil))) 当参数是(a (b) c) 您不需要做任何事情 - 这些已经相同(使用 identity :-)。

请看说明书:

具体来说:

Although the two expressions below are equivalent, and the reader accepts either one and produces the same cons, the printer always prints such a cons in the second form:

(a . (b . ((c . (d . nil)) . (e . nil))))
(a b (c d) e)

你可能是什么意思

如果你需要构造一个string "(a . ((b . nil) . (c . nil)))",你需要工作:

(defun cons-cell-diagram-string (x)
  (if (consp x)
      (format nil "(~A . ~A)"
              (cons-cell-diagram-string (car x))
              (cons-cell-diagram-string (cdr x)))
      (princ-to-string x)))
(cons-cell-diagram-string '(a (b) c))
==> "(A . ((B . NIL) . (C . NIL)))"

你可能还指的是什么

任务的另一种可能解释是返回一个列表,但将点作为字符串插入:

(defun cons-cell-diagram-list (x &optional (consing-dot "."))
  (if (consp x)
      (list (cons-cell-diagram-list (car x) consing-dot)
            consing-dot
            (cons-cell-diagram-list (cdr x) consing-dot))
      x))
(cons-cell-diagram-list '(a (b) c))
==> (A "." ((B "." NIL) "." (C "." NIL)))
(cons-cell-diagram-list '(a (b) c) '|.|)
==> (A |.| ((B |.| NIL) |.| (C |.| NIL)))
(cons-cell-diagram-list '(a (b) c) '#\.)
==> (A #\. ((B #\. NIL) #\. (C #\. NIL)))

附言

请注意,我根据普遍接受的 Lisp 编码标准随意格式化您的代码。

很明显,您在 listp 子句中有一个多余的 nil(在单独的一行上)。

您可能想使用 Emacs 来编辑您的代码。

关于列表的 lisp Cons 单元图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42648171/

相关文章:

lisp - Lisp中@(at-sign)的含义?

windows - 为什么 lisp 数到十亿这么慢?

lisp - 收集 `time`宏产生的时空结果?

LISP:如何获得列表的总和? (没有全局变量)

json - 如何在使用 cl-json 时输出 false

Lisp 用列表初始化变量

common-lisp - 是否有任何标准函数可以通过应用于单个值来遍历谓词?

clojure - 无法更改/建立 : [some-def] with set in Clojure 的根绑定(bind)

scheme - Common Lisp和Scheme之间的通用词汇

vector - 可扩展向量类型