Updated 2011-08-30 10:21:28 by RLE

if 0 {Richard Suchenwirth 2004-03-19 - I needed to generate lists of n-tuples from a set, i.e. subsets of fixed length (pairs, triples, ...) in canonical (lexicographic) ordering, like the pairs over {a b c d} being
 {a b} {a c} {a d} {b c} {b d} {c d}.

Here's code that does that for different values of n:}
 proc tuples {n set} {
    if {$n == 1} {return $set}
    set res {}
    incr n -1
    foreach i [lrange $set 0 end-$n] {
        set set [lrange $set 1 end]
        foreach t [tuples $n $set] {
           lappend res [linsert $t 0 $i]
        }
    }
    set res
 }

 % tuples 3 {a b c d}
 {a b c} {a b d} {a c d} {b c d}
 % tuples 4 {a b c d e}
 {a b c d} {a b c e} {a b d e} {a c d e} {b c d e}
 % tuples 2 {a b c d}
 {a b} {a c} {a d} {b c} {b d} {c d}