mercredi 2 juin 2021

The R function to analyze a body of a function given as an argument (computation flow)

I would like to get a function "getFlow()" -> the purpose of this function is to analyze a body of a function given as an argument. The analysis is concerned with assignments done within the body of an argument function. Technically, the getFlow() function takes a function as an argument (object with a base type closure) and returns an object containing a list of all assignments together with conditions (resulting from if / else phrases). Please see an example below:

### Function definition
f <- function(a, b) {
    b <- abs(b)
    x <- a ^ b
    x
}

fFlow <- getFlow(f)
fFlow

And the result should be following:

b  <-  abs(b)  ||| TRUE
x  <-  a^b     ||| TRUE

The getFlow() returns an object containing a list of assignments with conditions attached. In an implementation, the list of assignments is an instance of a new class assignmentList, and each element of this list is an instance of another new class assignment. For both classes, it implemented print methods and c methods for convenience. In the above example, the list contains a single element: an assignment with a condition TRUE indicating that this is an unconditional assignment.

Next, let's see how the getFlow() works for functions containing conditional statements.

### Function definition
f <- function(a, b) {
    x <- rnorm(1)
    if(a < 0)
    {
        a <- abs(a)
        if(b == 2L)
        {
            y <- a ^ 2
            y <- y + x
        }
    } else
    {
        y <- a ^ b
        y <- y + x
    }
    y
}

fFlow <- getFlow(f)
fFlow

And the result should be the following:

x  <-  rnorm(1)  ||| TRUE
a  <-  abs(a)    ||| a < 0  and TRUE
y  <-  a^2       ||| a < 0  and b == 2L  and TRUE
y  <-  y + x     ||| a < 0  and b == 2L  and TRUE
y  <-  a^b       ||| not a < 0  and TRUE
y  <-  y + x     ||| not a < 0  and TRUE

May you please provide me with the solution to this exercise without any additional R-packages except for stringr, if necessary? It will be very helpful to understand how it works

Aucun commentaire:

Enregistrer un commentaire