R, How does while (TRUE) work?

前端 未结 2 1746
长情又很酷
长情又很酷 2021-02-15 12:32

I have to write a function of the following method :

Rejection method (uniform envelope):

Suppose that fx is non-zero only on [a, b], and fx ≤ k.

2条回答
  •  情话喂你
    2021-02-15 13:13

    It's an infinite loop. The expression is executed as long as the condition evaluates to TRUE, which it will always do. However, in the expression there is a return, which when called (e.g., if y < fx(x)), breaks out of the function and thus stops the loop.

    Here is a simpler example:

    fun <- function(n) {
      i <- 1
      while (TRUE) {
        if (i>n) return("stopped") else print(i)
        i <- i+1
      }
    }
    
    fun(3)
    #[1] 1
    #[1] 2
    #[1] 3
    #[1] "stopped"
    

    What happens when this function is called?

    1. i is set to 1.
    2. The condition of the while loop is tested. Because it is TRUE, it's expression is evaluated.
    3. The condition of the if construct is tested. Since it is FALSE the else expression is evaluated and i is printed.
    4. i is increased by 1.
    5. Steps 3 and 4 are repeated.
    6. When i reaches the value of 4, the condition of the if construct is TRUE and return("stopped") is evaluated. This stops the whole function and returns the value "stopped".

提交回复
热议问题