by Guangming Lang
~1 min read

Categories

  • r

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

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

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

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