Version 7 of Set Functions

Updated 2003-07-03 11:41:02

Mathematical set based functions

Of obvious enough kind, but important, and underused, I guess. Page started by Theo Verelst

These are the first definitions:

 proc set:empty {}    {return {}}
 proc set:add {a b}   {return [set:union $a $b]}
 proc set:isempty {s} {expr {[set:size $s] == 0}}
 proc set:size {s}    {return [llength $s]}
 proc set:union {a b} {
    ## all elements in a and b once, join
    set o {}
    foreach i $a {
       if {[lsearch $b $i] < 0} {lappend o $i}
    }
    set o [concat $o $b]
    return $o
 }
 proc set:intersection {a b} {
    ## both in a and in b
    set o {}
    foreach i $a {
       if {[lsearch $b $i] >= 0} {lappend o $i}
    }
    return $o
 }
 proc set:restrict {a b} {
    # returns elements from a and not in b
    set o {};
    foreach i $a {
       if {[lsearch $b $i] < 0} {
          lappend o $i
       }
    }; 
    return $o
 }
 proc set:difference {a b} {
    ## what is this ([tv])?
    foreach i $b {
       if {[set idx [lsearch $a $i]] >= 0} {
          set a [lreplace $a $idx $idx]
       }
    }
    return $a
 }

Nice touch those renamings, now my examples don't work anymore.... (grin, TV)

 proc set:numbers {{to 10} {from 1}} {
    set o {}; 
    for {set i $from} {$i <= $to} {incr i} {
       lappend o $i
    }; 
    return $o
 }

Examples

 set:intersection [
    set:restrict [
       set:union [set:numbers 4] [set:numbers 10 6]
    ] {2 3}
 ] [set:numbers 7 3]

numbers 7 3 gives {3 4 5 6 7} numbers 4 gives {1 2 3 4} numbers 10 6 gives {6 7 8 9 10} union functions returns: {1 2 3 4 6 7 8 9 10} (5 missing) after restriction: {1 4 6 7 8 9 10} after intersection: {4 6 7}