Subject: Re: How do I define swap procedure ?
From: rpw3@rigden.engr.sgi.com (Rob Warnock)
Date: 1999/11/06
Newsgroups: comp.lang.scheme
Message-ID: <800vlq$3k5l6@fido.engr.sgi.com>
Jed Davis <Jed.Davis@mercury.cc> wrote:
+---------------
| If your scheme implementation supports define-macro, you can use:
| (define-macro
|     (swap v1 v2)
|         `(let ((tmp ,v1))
|             (set! ,v1 ,v2)
|             (set! ,v2 tmp)))
+---------------

Unlike the hygenic macros (define-syntax/syntax-rules), the define-macro
style [like defmacro] doesn't automatically provide protection from
unintended variable capture. So it would be safer to write it this way:

    (define-macro (swap v1 v2)
      (let ((tmp (gensym)))
	`(let ((,tmp ,v1))
	   (set! ,v1 ,v2)
	   (set! ,v2 ,tmp))))


-Rob

p.s. In case your Scheme doesn't have "gensym", here's a crude one:

(define gensym  
   (let ((n 0))
     (lambda ()
       (set! n (+ n 1))
       (string->symbol (string-append "G:" (number->string n))))))

-----
Rob Warnock, 8L-846		rpw3@sgi.com
Applied Networking		http://reality.sgi.com/rpw3/
Silicon Graphics, Inc.		Phone: 650-933-1673
1600 Amphitheatre Pkwy.		FAX: 650-933-0511
Mountain View, CA  94043	PP-ASEL-IA