[plt-scheme] Printing and Overloading

From: Eli Barzilay (eli at barzilay.org)
Date: Thu Mar 18 02:12:35 EST 2004

On Mar 18, Paulo Jorge de Oliveira Cantante de Matos wrote:
> 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?

This is not strictly in PLT-Scheme, but:

  winooski:~ eli> swindle
  => (defstruct <tuple> () x y)
  => (defmethod (add (t1 <tuple>) . more)
       (make-tuple (apply add (tuple-x t1) (map tuple-x more))
                   (apply add (tuple-y t1) (map tuple-y more))))
  => (defmethod (print-object (t <tuple>) esc? port)
       (echo :> port :s- :n- "(" (tuple-x t) ", " (tuple-y t) ")"))
  => (add (make-tuple 1 2) (make-tuple 3 4))
  (4, 6)

Also:

  => (add (make-tuple (make-tuple 1 2) "ab")
          (make-tuple (make-tuple 3 4) "cd"))
  ((4, 6), abcd)

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!


Posted on the users mailing list.