Functions that Return Functions

Master R

By Guangming Lang Comment

I love the idea of writing a function that returns another function. For example, say we want to compute for any given and . We can write a function that takes as input and returns a function, which can further take as input and returns the result. Here’s the R code:

make.power = function(n) {
    function(x) x^n

Say we want to find , we can first run make.power(2) to construct a function that will square any passed to it. Let’s call it power2. We can then use power2(x) to calculate for any value. For example, power2(3) gives the value of , and power2(5) gives the value of , and etc.

power2 = make.power(2)
## [1] 9
## [1] 25

If you enjoyed this post, get updates. It's FREE