11.1 Introduction

  • A function operator is a function that takes one (or more) functions as input and returns a function as output.

  • Function operators are a special case of function factories, since they return functions.

  • They are often used to wrap an existing function to provide additional capability, similar to python’s decorators.

chatty <- function(f) {
  force(f)
  
  function(x, ...) {
    res <- f(x, ...)
    cat("Processing ", x, "\n", sep = "")
    res
  }
}

f <- function(x) x ^ 2
s <- c(3, 2, 1)

purrr::map_dbl(s, chatty(f))
#> Processing 3
#> Processing 2
#> Processing 1
#> [1] 9 4 1