【问题标题】:R: How to make a switch statement fallthroughR:如何使 switch 语句失败
【发布时间】: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


【解决方案1】:

似乎switch() 无法实现这种行为。 正如 cmets 中所建议的,最好的选择是实现我自己的版本。


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

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

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

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2021-07-19
    • 2016-12-05
    • 2012-09-05
    • 2012-05-10
    • 2021-02-28
    相关资源
    最近更新 更多