R: How to make a switch statement fallthrough
在许多语言中,有一个名为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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而导致错误,但默认情况下,有几种语言正在中断,并包含fallthrough关键字(例如,Perl中的
根据设计,R开关在每种情况结束时也默认断开:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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!") } ) |
在上述代码中,如果
R中是否有任何方法强制开关箱从以下情况中跌落?
似乎这种行为在
因此,我对我的
通过这个更新,您现在可以在模式匹配函数
问题中的设计模式可以通过以下方式复制:
1 2 3 4 5 6 7 8 9 | 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..." |
您可以观察到,
1 2 3 4 5 6 7 8 9 | 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" |