Version 1 of Nested list join

Updated 2002-11-27 19:30:55

Richard Suchenwirth 2002-11-27 - A visitor in the Tcl chatroom asked for a modified foreach to cover all combinations of the input lists. In database technical terms, this is called a "nested list join", at least one functional programming tutorial tells me so.

Well, and reason enough to do some Tcl'ing - from the input, build up a nested command of foreaches, insert the specified body in the middle, and presto:

 proc foreach2 args {
    set body [lindex $args end]
    set cmd ""
    foreach {vars list} [lrange $args 0 end-1] {
       append cmd "[list foreach $vars $list] \{\n"
       append body "\}"
    }
    uplevel 1 $cmd$body
 }

#------------------------- Testing:

 % foreach2 x {a b} y {c d} {puts x:$x,y:$y}
 x:a,y:c
 x:a,y:d
 x:b,y:c
 x:b,y:d

No error-checking yet - the length of args must be odd and >2. Caveat user.


Category Concept | Arts and crafts of Tcl-Tk programming