繁体   English   中英

R:如何制作切换声明

[英]R: How to make a switch statement fallthrough

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

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语句,这可能会导致错误,但是默认情况下会破坏几种语言,并包含一个fallthrough关键字(例如,在Perl中continue )。

按照设计,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()无法实现这种行为。 正如评论中所建议的那样,最好的选择是实现我自己的版本。


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

通过此更新,您现在可以在模式匹配函数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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM