[Openmcl-devel] square bracket list

Joshua TAYLOR joshuaaaron at gmail.com
Sun Jul 24 10:08:24 PDT 2011


On Sun, Jul 24, 2011 at 6:07 AM, Taoufik Dachraoui
<dachraoui.taoufik at gmail.com> wrote:
> to be more precise, is there a way to print lists depending on the car
> of the list
>  (cond
>   ((eq (car lst) #\[) (print list using [...]))
>   ((eq (car lst) #\{) (print list using {...}))
>   (t (print list using (...))))

Pascal already responded with a solution that you said works for you.
Here's one that's a bit shorter, and uses the lisp pretty printer.
Pretty print dispatch tables dispatch to a printing function based on
matching type specifiers to objects, and fortunately there's a (cons
car-type cdr-type) type specifier, and an (eql X) type specifier, so
your special lists can be matched.  E.g.,

CL-USER > (typep '(#\[ 1 2 3) '(cons (eql #\[) t))
T

So, here's a solution using that technique:



(defparameter *list-pprint-dispatch*
  (copy-pprint-dispatch))

(defun special-list-printer (left right)
  #'(lambda (stream list)
      (pprint-logical-block (stream list :prefix left :suffix right)
        (pprint-linear stream (rest list) nil))))

(set-pprint-dispatch '(cons (eql #\[) t)
                     (special-list-printer "[" "]")
                     0 *list-pprint-dispatch*)

(set-pprint-dispatch '(cons (eql #\{) t)
                     (special-list-printer "{" "}")
                     0 *list-pprint-dispatch*)

(defun special-print (object)
  (write object
         :pprint-dispatch *list-pprint-dispatch*
         :pretty t))



Basic usage:

CL-USER 10 > (special-print '(1 2 (#\[ 3 4) (#\{ 5 6) 7 8))
(1 2 [3 4] {5 6} 7 8)
(1 2 (#\[ 3 4) (#\{ 5 6) 7 8)

Since it uses the pretty printer, it can even deal with long lists and
circular structures (sort of;  the result won't be READable,
obviously):

CL-USER 12 > (special-print `(1 2 (#\[ ,@(make-list 20) (#\{ 5 6) 7 8)))
(1
 2
 [NIL
  NIL
  ...
  NIL
  NIL
  {5 6}
  7
  8])

CL-USER 15 >
(let ((sq (list 3 4)))
  (nconc sq sq)
  (special-print (list 1 2 (cons #\{ sq) 5 6)))
(1 2 {#1=3 4 . #1#} 5 6)

Hope this is of interest to you.

//JT

-- 
Joshua Taylor, http://www.cs.rpi.edu/~tayloj/



More information about the Openmcl-devel mailing list