Self Application Function
The function λx.x x
is the self application function. It applies its argument to its argument.
// λx.x x
const sa = x => x(x)
Like the identity function, it doesn't seem helpful at first glance but it has some interesting applications. Consider the twice function λf.λx.f (f x)
, which applies function f
to the value x
and then applies function f
again to the result of that.
// λf.λx.f (f x)
const twice = f => x => f(f(x))
const addOne = a => a + 1
twice(addOne)(1) // 3
By supplying the twice
function with the addOne
function, and then supplying the resulting function with 1
, we get 3
. That's because twice(addOne)(1)
is the same as addOne(addOne(1))
or 1 + 1 + 1
.
Going back to the self application function, since it applies its argument to its argument, given the function twice
, it will apply twice
to twice
, applying the addOne
function four times.
// λx.x x
const sa = x => x(x)
// λf.λx.f (f x)
const twice = f => x => f(f(x))
// (λx.x x) (λf.λx.f (f x))
const fourTimes = sa(twice)
const addOne = a => a + 1
fourTimes(addOne)(1) // 5