Home > Back-end >  how to use filter the numbers from list using foreach and if?
how to use filter the numbers from list using foreach and if?

Time:10-19

set A { 50 98 76 34 67}
set B { 12 23 48 59 65}

foreach c $A d $B {
    if { (40 <= $c && $c <= 60) || (20 <= $d && $d <= 30) } {
      puts $c
      puts $d
    }
}

I am getting output as 50 12 98 23 but it should be 50 and 23.

CodePudding user response:

You seem to be quite confused as to what the consequences of the code you have written really are.

That foreach presents the pair-wise elements from the two lists to the body script via the variables. That is, you get 50,12, then 98,23, then 76,48, ...

Your body script consists of a single if with one test (which happens to be a compound expression, but it is still a single test overall), and will run its body if that test is true.

The body prints both variables.

That is what you have told the language to do. It has done it for you. The computer can't read your mind; the only way it can know what to do is because someone has told it what to do.


I guess you might like:

set A { 50 98 76 34 67}
set B { 12 23 48 59 65}

foreach c $A d $B {
    if {40 <= $c && $c <= 60} {
        puts $c
    }
    if {20 <= $d && $d <= 30} {
        puts $d
    }
}

Or even this:

proc when {value in range from to do body} {
    if {$from <= $value && $value <= $to} {
        uplevel 1 $body
    }
}

set A { 50 98 76 34 67}
set B { 12 23 48 59 65}

foreach c $A d $B {
    when $c in range 40 60 do {puts $c}
    when $d in range 20 30 do {puts $d}
}

Once you understand why this works, you'll be much further on with your understanding of both Tcl and programming in general.

CodePudding user response:

Is this meant to be a pairwise XOR (exclusive-or)? If so, the inclusive-or || operator will not help.

You might consider rewriting to:

set A {50 98 76 34 67}
set B {12 23 48 59 65}

foreach c $A d $B {
  if {40 <= $c && $c <= 60} {
    puts $c
  } elseif {20 <= $d && $d <= 30} {
    puts $d
  }
}
  • Related