Mathematical set based functions
Of obvious enough kind, but important, and underused, I guess. Page started by [Theo Verelst]
See also [Chart of proposed set functionality] for other 'set' functions on the wiki.
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}
----
I'm not finished with the subject, but I found there are more pages and progams about the subject, in fact comparable, I don't remember the titles, but they were bigger pages even..
However, what is the/my point? That it is good to have decent and useable and readable set handling, when dealing with various programming problems, function evaluation and domain/range setting/verification, database type of data handling, and very much when making fundamental programming blocks, for instance intended for such graph based programs like [bwise] where using set, functions, the rigth decomposition and maybe some inversion tools, completely correct programming of important fundamental problems is possible.
For good instance computer logic circuits, and their direct extension to logical problems and reasoning. For the moment I see it as educational and fundamental tries, but I 'tried' a database in tcl, too, and that works fine with quite serious dataset. And then works as one bwise block, too.