Tcl中If-Else的更好替代方案

时间:2014-04-09 08:07:47

标签: arrays if-statement tcl conditional-statements

我有一个如下所示的表,我需要在Tcl中编写代码。我尝试了if-else代码但是它们变成了非常长且重复的句子。是否有更好的替代解决方案来实现使用数组或switch case语句或类似的东西

Table

Number Condition Width Height
2         True     1x    1y
3         True     1x    1y
4         True     1x    2y
5         True     2x    2y
6         True     2x    4y
7         True     3x    4y
2         False    0.2x  1y
3         False    0.2x  1y
4         False    0.2x  1y
5         False    0.2x  1y
6         False    0.2x  1y
7         False    0.2x  1y

基本上,这个宽度和高度我正在检查标准的已知值,所以我使用mod函数将值存储到变量中,然后应用相同的条件。

例如:让我们考虑已知值为100和1x = 10和1y = 20 10和20都可以被100整除,因此mod函数显然会返回0。

所以,我会检查这样的事情:

set knownvalue 100
set 1x 10
set 1y 20
set offset_x [expr ($knownvalue % $1x)]
$> 0                                # (return 0)
set offset_y [expr ($knownvalue % $1y)]
$> 0                                #(returns 0)`

#  (Note as per chart for number 2, Height becomes 2y so that needs to be accounted for when calculating $offset_2y)

在现实生活中,上面显示的表的1x和1y将会改变,因此我使用以下代码技术:

if {condition == true} {
     if {(number ==2 || number ==3) && ( $offset_x != 0)} {
     puts "Error"
     }
     if {number ==4 && ($offset_x !=0 || $offset_2y != 0)} {
     puts "Error"                                   
     }
     ..... complete till number ==7
} else {
    if {(number ==2 || number ==3 || number ==4 ... number ==7) && (offset_0.2x !=0 ||         $offset_1y !=0 )} {
    puts "Error"
}

这虽然有效,但并不是实现这一目标的最佳解决方案。所以,请提出更好的建议。

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果您可以构建表,以便检查特定类别的成员资格是相等性测试的集合,则可以将其转换为关联数组查找。如果您将关联数组中变量的内容设为脚本,则可以只计算要评估的代码并使用它。

set action(2,true,0,0) {error "Something went wrong"}
#...

eval $action($number,$condition,[expr {$offset_x % 10}],[expr {$offset_y % 42}])

但是,只有 才可以构建,以便您进行精确的字符串查找。特别是,上面可能就像你在做的那样:

if {($number eq "2") && ($condition eq "true") && ($offset_x % 10 eq "0") && ($offset_y % 42 eq "0")} {
    error "Something went wrong"
} else ...

如果失败,请尝试switch命令。这至少可以支持默认情况和glob模式:

switch -- $number,$condition,[expr {$offset_x % 10}],[expr {$offset_y % 42}] {
    2,true,0,0 - 7,false,1,19 {
        error "Something went wrong"
    }
    default {
        puts "nothing else applicable"
    }
}
switch -glob -- $number,$condition,[expr {$offset_x % 10}],[expr {$offset_y % 42}] {
    2,true,0,* - 7,false,*,19 {
        error "Something went wrong"
    }
    default {
        puts "nothing else applicable"
    }
}