3

在许多语言中,有一条名为的指令break告诉解释器在当前语句之后退出 switch。如果省略它,则在处理当前案例后切换:

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 语句,这可能会由于无意的失败而导致错误,但是默认情况下有几种语言会中断,并包含一个失败关键字(例如continue在 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中是否有任何方法可以强制开关盒通过以下情况?

4

1 回答 1

1

看来这种行为是不可能的switch()。正如评论中所建议的,最好的选择是实现我自己的版本。


因此,我将更新推送到我的optional包以实现此功能 ( CRAN )。

通过此更新,您现在可以在模式匹配函数中使用 fallthrough 语句match_with

问题中的设计模式可以通过以下方式重现:

library(optional)
a <- 1
match_with(a
    1, fallthrough(function() "Processing the first step..."),
    2, fallthrough(function() "Processing the second step..."),
    3, function() "Processing the third step...",
    4, function() "All steps have already been processed!"
)
## [1] "Processing the first step..." "Processing the second step..." "Processing the third step..."

您可以观察到它match_with()与 非常相似switch(),但它具有扩展功能。例如,模式可以是列表或功能序列,而不是简单的比较对象:

library("magrittr")
b <- 4
match_with(a,
  . %>% if (. %% 2 == 0)., 
  fallthrough( function() "This number is even" ),
  . %>% if ( sqrt(.) == round(sqrt(.)) ).,  
  function() "This number is a perfect square"
)
## [1] "This number is even" "This number is a perfect square"
于 2018-05-06T07:49:49.840 回答