user14361571
user14361571

Reputation:

How to perform selective removal based on value from a list in TCL?

Considering a list like {100 169 144 289}, what is the best way to remove odd squares 169,289 as in the example list here?

Upvotes: 0

Views: 98

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

The easiest method is to filter the list. Depending on the nature of the condition, the main techniques are lsearch -all -inline (possibly with -not) for something that can be expressed as a string pattern, and lmap for the rest. In your case, we can do:

set filtered [lmap x $input {
    if {$x & 1} then continue else {set x}
}]

The trick here is that a continue in the body of an lmap skips the adding of the value to the output list, and set x reads the value of x. The result is to skip all odd numbers (because $x & 1 is an expression that is true when x holds an odd number) and otherwise to add to the list. The expression can be as complex as you want. (To overwrite, just do set input [lmap ...] instead of set filtered [lmap ...]. Keep them separate when testing.)

Upvotes: 2

Related Questions