Hello,

May I ask why R7RS seems to limit the gcd function to integers? I'm wondering 
since gcd extends to complex numbers, and so it could be defined as (gcd z1 
...). For example,

   (gcd 4+7i 9+17i)  ==>  2+i  and
   (gcd 4 7+i)       ==>  1+i.

Please find below a proof-of-concept implementation.

By the way: Has anyone attempted to implement the full R7RS numeric tower in a 
portable Scheme library, only using e.g. + - * / on fixed integers as a basis? 
(Just curious!)

All the best,
Fredrik

(define (extended-gcd w z)
 (letrec ((loop
   (lambda (w z a b c d)
     ; Solve [ a b | w ]
     ;       [ c d | z ].
     (cond ((= w 0) (values z c d))
           ((= z 0) (values w a b))
           ((or (<= (real-part w) 0) (< (imag-part w) 0))
            (loop (* w 0+i) z (* a 0+i) (* b 0+i) c d))
           ((or (<= (real-part z) 0) (< (imag-part z) 0))
            (loop w (* z 0+i) a b (* c 0+i) (* d 0+i)))
           ((<= (magnitude w) (magnitude z))
            (let ((q (floor (/ (magnitude z) (magnitude w)))))
              (loop w (- z (* w q)) a b (- c (* a q)) (- d (* b q)))))
           (else (loop z w c d a b))))))
   (loop w z 1 0 0 1)))

(define (complex-gcd . ops)
 (cond ((null? ops) 0)
       ((null? (cdr ops)) (car ops))
        (else (call-with-values
               (lambda () (extended-gcd (car ops) (apply complex-gcd (cdr 
ops))))
               (lambda (z m n) z)))))

(define gcd complex-gcd)
_______________________________________________
Scheme-reports mailing list
[email protected]
http://lists.scheme-reports.org/cgi-bin/mailman/listinfo/scheme-reports

Reply via email to