简体   繁体   中英

Evaluating (…) in a function argument in R

I have the following functions:

ignore <- function(...) NULL
tee <- function(f, on_input = ignore, on_output = ignore) {
function(...) {
    on_input(...)
    output <- f(...)
    on_output(output)
    output
  }
}

My question would be on how is the (...) expression evaluated in the on_input in the tee function? I understand that in the case of ignore function, it will simply take any arguments and still return a NULL value. However, I am unsure if on_input and on_output are functions and also on what will happen to the on_input and output function in this case?

you took that code from Wickham Book Advanced R. In this book you can find an example

g <- function(x) cos(x) - x
zero <- uniroot(g, c(-5, 5))
show_x <- function(x, ...) cat(sprintf("%+.08f", x), "\n")

# The location where the function is evaluated:
zero <- uniroot(tee(g, on_input = show_x), c(-5, 5))

You can imagine that on_input and on_output are function that work with the input and the output of the function. In this case for example you are printing the input of each iteration on the g function.

zero <- uniroot(tee(g, on_output = show_x), c(-5, 5))

On this case on the contrary you are printing the output of the function on each iteration.

To summarise, yes on_input and on_output are functions and this function simply work with the input and the output of the function f.

EDIT

Just an easier example to understand what is going on

pow2<-function(x){x^2}
input<-function(x){
  cat(paste("input is ",x,"\n",sep=""))
}
output<-function(x){
  cat(paste("output is ",x,"\n",sep=""))
}

tee(pow2,on_input=input,on_output=output)(2)

input is 2
output is 4
[1] 4

the main function here is obviously pow2

tee take pow2 and return a function that run on_input, pow2 and on_output.

Notice also that you have to call and pass an argument to the result of tee, in fact tee is returning a function and not a value

(...) match all additional arguments passed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM