fork(1) download
  1. ;; Generate combinations. (1.02)
  2.  
  3. (use-modules (srfi srfi-1))
  4.  
  5. ;; Utility.
  6.  
  7. (define (pair-map proc l)
  8. (pair-fold-right (lambda (item init)
  9. (cons (proc item) init))
  10. '() l))
  11.  
  12. (define (pair-append-map proc l)
  13. (apply append (pair-map proc l)))
  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. ;; Show.
  27.  
  28. (define n 5)
  29. (define a (iota n 1))
  30. (for-each (lambda (k)
  31. (format #t "~A choose ~A~%" n k)
  32. (for-each (lambda (c)
  33. (format #t " ~A~%" c))
  34. (combinations a k)))
  35. (iota n 1))
Success #stdin #stdout 0.02s 10936KB
stdin
Standard input is empty
stdout
5 choose 1
 (1)
 (2)
 (3)
 (4)
 (5)
5 choose 2
 (1 2)
 (1 3)
 (1 4)
 (1 5)
 (2 3)
 (2 4)
 (2 5)
 (3 4)
 (3 5)
 (4 5)
5 choose 3
 (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)
5 choose 4
 (1 2 3 4)
 (1 2 3 5)
 (1 2 4 5)
 (1 3 4 5)
 (2 3 4 5)
5 choose 5
 (1 2 3 4 5)