Reputation: 11
I have an assignment to write a code in high order function (Function 1). However, I do not know why I should write it like that instead of normal one (Function 2). I would really appreciate if someone could show me when High order function is better.
# Function 1 (High order):
def high_function (L):
def function (x):
total = 0
for i in range(len(L)):
total = total + x **(len(L) - 1 - i) * L[i]
return total
return function
# Function 2 (Normal):
def high_function (L, x):
total = 0
for i in range(len(L)):
total = total + x **(len(L) - 1 - i) * L[i]
return total
Upvotes: 1
Views: 1161
Reputation: 2480
I lack formal knowledge of functional programming, but in essence, having higher order functions allows you to create functions as needed and pass them to other higher order functions.
Just like objects can take in other objects, languages that treat functions as first class citizens allow functions to be passed into other functions.
Consider this example,
def add(a):
def func(b):
return a + b
return func
This add
function can be used to create functions as needed
twoMore = add(2)
x = 10
xPlusTwo = twoMore(x)
Note that when you create a function within a function, the inner function is within a closure and has access to the scope of the outer function. In the case of the add
function, the inner func
has access to a
when it returned by add
and used in twoMore
.
Just to conclude my point about passing functions around, consider this other example
def filter_list(valid, list):
return [item for item in list
if valid(item)]
def is_greater_than(value):
def func(item):
return item > value
return func
my_list = [1,2,3,4,5,6,7]
gt5 = is_greater_than(5)
new_list = filter_list(gt5, my_list)
Upvotes: 0
Reputation: 42758
First, give your functions a better name, so the usage is more clearly:
def polynomial(factors):
def eval(x):
result = 0
for factor in factors:
result = x * result + factor
return result
return eval
So the function is used to define a polynomial, which can be used to evaluate for different x
:
parabola = polynomial([1, 0, 0])
And to use it somewhere else:
value = parabola(0.4)
Upvotes: 2