【发布时间】:2021-05-04 20:12:02
【问题描述】:
在许多语言中,有一条名为break 的指令告诉解释器在当前语句之后退出开关。如果省略,则当前案例处理完毕后的开关fall-through:
switch (current_step)
{
case 1:
print("Processing the first step...");
# [...]
case 2:
print("Processing the second step...");
# [...]
case 3:
print("Processing the third step...");
# [...]
break;
case 4:
print("All steps have already been processed!");
break;
}
如果您想通过一系列传递条件,这种设计模式会很有用。
我知道如果程序员忘记插入 break 语句,这可能会由于无意的失败而导致错误,但有几种语言默认会中断,并包含一个失败关键字(例如continuein Perl)。
根据设计,R 开关也会在每个案例结束时默认中断:
switch(current_step,
{
print("Processing the first step...")
},
{
print("Processing the second step...")
},
{
print("Processing the third step...")
},
{
print("All steps have already been processed!")
}
)
在上面的代码中,如果current_step设置为1,则输出只会是"Processing the first step..."。
R 中是否有任何方法可以强制 switch 案例通过以下案例?
【问题讨论】:
-
stackoverflow.com/a/17113744/1457051 是你能做到的最好的。
-
@hrbrmstr 它很接近但仍然不是真正的失败,这个解决方案只允许一个案例有多个标签。
-
@Lovy - 如果您不喜欢 R
switch()语句的行为,您可以随时编写自己的版本。 -
@Lovy 我知道。我说“你能做到的最好”是有原因的。欢迎随时reimplement the primitive。
标签: r switch-statement fall-through