fork(2) download
  1. ;; Pythagorean triples using combinations.
  2.  
  3. (use-modules (srfi srfi-1))
  4.  
  5. (define (combinations sequence k yield)
  6. (let loop ((rest sequence) (n k) (out '()))
  7. (if (zero? n)
  8. (yield (reverse out))
  9. (pair-for-each (lambda (p)
  10. (loop (cdr p) (- n 1) (cons (car p) out)))
  11. rest))))
  12.  
  13. (define (primitive-pythagorean-triple? x y z)
  14. (and (< x y z)
  15. (= (+ (* x x) (* y y)) (* z z))
  16. (= (gcd x y z) 1)))
  17.  
  18. (define (pythagorean-triples n)
  19. (let ((out '()))
  20. (combinations (iota n 1) 3
  21. (lambda (v)
  22. (apply (lambda (x y z)
  23. (when (primitive-pythagorean-triple? x y z)
  24. (set! out (cons v out))))
  25. v)))
  26. (sort out (lambda (x y) (< (third x) (third y))))))
  27.  
  28. (for-each (lambda (x) (format #t "~A~%" x)) (pythagorean-triples 53))
Success #stdin #stdout 0.12s 12032KB
stdin
Standard input is empty
stdout
(3 4 5)
(5 12 13)
(8 15 17)
(7 24 25)
(20 21 29)
(12 35 37)
(9 40 41)
(28 45 53)