tags:

views:

117

answers:

2

Hi guys,I have a small and interesting problem,but I cannot come with a perfect solution,I would be grateful if you could help me or give me a hint on this. The problem is :

given any list ,say like '(a b c),we will convert it to '[a b c] or '(a (b c)) ,we will convert to '[A [B C]]

In other words,the function should do the same thing as PRINT in LISP,except we change the parentheses to square brackets.But methods like simply printing to a string then replace the parentheses to square brackets don't count. Please give me some idea,thank you.

A: 

This is a great book: Practical Common Lisp.

You might want to start here if you're in a hurry: List Processing and Format Recipes

A: 

Here's my take:

(defun bprint (object)
  (typecase object
    (cons
     (write-char #\[)
     (do ((list object (rest list)))
         ((endp list) (write-char #\]))
       (bprint (first list))
       (when (rest list)
         (write-char #\Space))))
    (t
     (prin1 object)))
  t)

That is: when encountering a list, print an opening bracket, print the contents recursively, adding a space after an object if necessary, then print a closing bracket. Print all non-list objects with prin1. prin1 is the "produce READable output" printer.

Xach