Version 3 of comb

Updated 2004-06-11 07:43:35

Richard Suchenwirth 2004-06-10 - A little challenge in Tcl programs for beginners made me rebake an earlier half-baked idea: the pattern of a data comb which returns some string depending on a numeric value and a specification, which gives the possible strings and the borderline values, e.g. (in Centigrades):

 {"bitter cold" -10 cold 10 fresh 15 nice 25 warm 30 hot}

You can consider the odd elements of this list (starting from 1, or the second one) as being the comb's teeth, and the even elements as the results to return when the tested value lies between two teeth (or outside). The rules are crystallized into a compact form (which is transparent pure-value), as opposed to the more C-like style

 if {$x<-10} {
     set res "bitter cold"
 } elseif {$x<10} {
     set res "cold"
 } elseif {$x<15} {
     set res "fresh"
 } elseif {$x<25} {
     set res "nice"
 } elseif {$x<30} {
     set res "warm"
 } else {
     set res "hot"
 }

which shows the comb structure, but disperses the data over different locations in the code.

The code for comb is of course pretty easy:

 proc comb {x spec} {
    foreach {value limit} $spec {if {$x<$limit} {return $value}}
    return $value
 }

# Testing:

 % comb 11 {child 13 teen 19 adult}
 child
 % comb 15 {child 13 teen 19 adult}
 teen
 % comb 99 {child 13 teen 19 adult}
 adult

Arts and crafts of Tcl-Tk programming