Reputation: 6833
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.
Upvotes: 2
Views: 1704
Reputation: 11854
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.
Upvotes: 2
Reputation:
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
Upvotes: 0