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)
power2(3)
## [1] 9
power2(5)
## [1] 25

You can read Steve Losh’s post for a thorough treatment, where he showed numbers are really made of lists, and lists are really just functions that returns other functions.

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