簡體   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