[plt-scheme] Printing and Overloading

From: Bruce Hauman (bhauman at cs.wcu.edu)
Date: Wed Mar 17 20:36:59 EST 2004

Paulo Jorge de Oliveira Cantante de Matos wrote:
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme
> 
> Hi all,
> 
> I've been thinking about this lately bout I've not had the time to try
> things out. However, as the result of some hours of research I found
> nothing in PLT Scheme that allows me to easily do one of the following
> things:
> 
> Imagine I have a structure/class tuple (x1, x2) and I want to:
> 
> 1. Overload primitive +, so that (+ (make-tuple 2 3) (make-tuple 2 3))
> gives me (4, 6).
> 
> 2. Print the tuple so that (write (make-tuple 2 3)) or even (format "~a"
> (make-tuple 2 3)) prints something like "(2, 3)".
> 
> Is there anyway to do this in PLT-Scheme? If there is, can somebody
> please explain it or direct me to the main references? 
> 
> Cheers, 

Hey again,

Here is a version without the match syntax.

(define-struct tuple (x y) (make-inspector))

(define +
   (let ((old+ +))
     (lambda args
       (if (andmap tuple? args)
           (make-tuple
            (apply + (map tuple-x args))
            (apply + (map tuple-y args)))
           (apply old+ args)))))

If you are using structs you might want to look up the
print-struct parameter to ease your printing.  The (make-inspector)
arg to the define-struct allows the printing of values in the struct.

Example:
(write (+ (make-tuple 1 2) (make-tuple 1 2)))
=> #<struct:tuple>
(print-struct #t)
(write (+ (make-tuple 1 2) (make-tuple 1 2)))
=> #(struct:tuple 2 4)




Posted on the users mailing list.