Below is the function repeat
written using a functional paradigm, such that when called as repeat(square, 2)(5)
it will apply the square
function 2
times on the number 5
, something like square(square(5))
.
def repeat(f, n):
def identity(x):
return x
def apply_n_times(n):
def recursive_apply(x):
return apply_n_times(n - 1)(f(x))
if n < 0:
raise ValueError("Cannot apply a function %d times" % (n))
elif n == 0:
return identity
else:
return recursive_apply
return apply_n_times(n)
def square(x):
return mul(x, x)
With regards to abstraction, I see that repeat(square, 2)
returns an implementation detail in the form of apply_n_times(n - 1)(f(x))
multiple times before providing the actual result.
With regards to encapsulation, for the expression f = repeat(square, 2)
one could mutate the members of function object, for example: f.__name__='garbage'
Does the concept of higher order function
allow supporting abstraction and encapsulation? Because they return the implementation details and provide access for mutation.
Such existing implementations in large software are very tedious to use, as the user has to have an idea of the implementation before using it.