fork(1) download
  1. ;; Pythagorean triples using combinations. (1.01)
  2.  
  3. (use-modules (srfi srfi-1))
  4.  
  5. ;; Utility.
  6.  
  7. (define (pair-map proc sequence)
  8. (pair-fold-right (lambda (item init)
  9. (cons (proc item) init))
  10. '() sequence))
  11.  
  12. (define (pair-append-map proc sequence)
  13. (apply append (pair-map proc sequence)))
  14.  
  15. ;; Combinations.
  16.  
  17. (define (combinations sequence k)
  18. (if (zero? k)
  19. (list '())
  20. (pair-append-map (lambda (rest)
  21. (map (lambda (comb)
  22. (cons (car rest) comb))
  23. (combinations (cdr rest) (- k 1))))
  24. sequence)))
  25.  
  26. ;; Pythagorean triples.
  27.  
  28. (define (primitive-pythagorean-triple? x y z)
  29. (and (< x y z)
  30. (= (+ (* x x) (* y y)) (* z z))
  31. (= (gcd x y z) 1)))
  32.  
  33. (define (pythagorean-triples n)
  34. (sort
  35. (filter-map
  36. (lambda (triple)
  37. (apply (lambda (x y z)
  38. (if (primitive-pythagorean-triple? x y z)
  39. triple
  40. #f))
  41. triple))
  42. (combinations (iota n 1) 3))
  43. (lambda (x y) (< (third x) (third y)))))
  44.  
  45. ;; Show.
  46.  
  47. (define n 5)
  48. (define a (iota n 1))
  49. (for-each (lambda (k)
  50. (format #t "~A~%" (combinations a k)))
  51. (iota n 1))
  52. (newline)
  53. (format #t "~A~%" (pythagorean-triples 53))
Success #stdin #stdout 0.15s 16104KB
stdin
Standard input is empty
stdout
((1) (2) (3) (4) (5))
((1 2) (1 3) (1 4) (1 5) (2 3) (2 4) (2 5) (3 4) (3 5) (4 5))
((1 2 3) (1 2 4) (1 2 5) (1 3 4) (1 3 5) (1 4 5) (2 3 4) (2 3 5) (2 4 5) (3 4 5))
((1 2 3 4) (1 2 3 5) (1 2 4 5) (1 3 4 5) (2 3 4 5))
((1 2 3 4 5))

((3 4 5) (5 12 13) (8 15 17) (7 24 25) (20 21 29) (12 35 37) (9 40 41) (28 45 53))