Reputation: 4055
There are a number of R functions which can take values passed to them from external operators. For example: names(mydata)<-c("x1","x2","x3")
or ggplot(mydata, aes(x=x,y=y))+geom_point()
.
Say I wanted to write a shortened function mapping the function "names":
nm <- names
> nm(mydata)
[1] "x" "y"
.... unknown code
nm(mydata) <- c("x1","x2")
> nm(mydata)
[1] "x1" "x2"
Upvotes: 2
Views: 107
Reputation: 2827
I would direct you to an excellent post on Function operators by Hadley Wickham. Hadley has a ton of code examples listed there with clear explanations. An example that Hadley uses to illustrate function operators is his code written for a simple function chatty(). This is the initial simple code that is provided for the function:
library(parallel)
chatty <- function(f) {
function(x) {
res <- f(x)
cat(format(x), " -> ", format(res, digits = 3), "\n", sep = "")
res
}
}
Below, you can see us call the function:
s <- c(0.4, 0.3, 0.2, 0.1)
x2 <- lapply(s, chatty(Sys.sleep))
The output from the function call is:
#> 0.4 -> NULL
#> 0.3 -> NULL
#> 0.2 -> NULL
#> 0.1 -> NULL
Here is an alternative application using mclapply:
x2 <- mclapply(s, chatty(Sys.sleep))
Here is the output:
#> 0.3 -> NULL
#> 0.4 -> NULL
#> 0.1 -> NULL
#> 0.2 -> NULL
In terms of using function operators in other programming languages (since you had asked about the definition of this phenomenon), Hadley reinforces the fact that they are very common across programming languages. As Hadley writes (and I quote):
Function operators are used extensively in FP languages like Haskell, and commonly in Lisp, Scheme and Clojure.
They are an important part of JavaScript programming, like in the underscore.js library.
They are particularly common in CoffeeScript because its syntax for anonymous functions is so concise.
Python's decorators are just function operators by a different name.
In Java, they are very rare because it's difficult to manipulate functions (although possible if you wrap them up in strategy-type objects).
They are also rare in C++ because, while it's possible to create objects that work like functions ("functors") by overloading the () operator, modifying these objects with other functions is not a common programming technique. That said, C++ 11 includes partial application (std::bind) as part of the standard library.
Upvotes: 1