简体   繁体   中英

lisp Cons cell diagram for the list

This is my trying code.

(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))

My goal is (f '(a (b) c)) should return (a . ((b . nil) . (c . nil))) .

Or (f '(ab)) should return (a . (b . nil)) .

This mean is process cons cell.

How do I fix it?

Another thing I wonder process symbol.

To process the symbol I use try (format t " . ") and recursively to print list,

But it's not going well.

Where should I start modify?

What you said

To return (a . ((b . nil) . (c . nil))) when the argument is (a (b) c) you don't need to do anything - these to are the same already (use identity :-).

Please take a look at the manual:

Specifically:

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)))) (ab (cd) e) 

What you probably meant

If you need to construct a string "(a . ((b . nil) . (c . nil)))" , you would need to work:

(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)))"

What you might also have meant

Another possible interpretation of the task is to return a list but insert dots as strings:

(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)))

PS

Please note that I took liberty to format your code according to the commonly accepted Lisp coding standards.

It becomes immediately obvious that you have a superfluous nil (on a separate line) in the listp clause.

You might want to use Emacs to edit your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM