Sobes.tech
Junior
199

What is a higher-order function?

Answer from AI

sobes.tech AI

A function that:

  1. Accepts one or more other functions as arguments.
  2. Returns another function as a result.
# Example of a higher-order function
def apply_function(func, x):
    # Takes a function 'func' and a value 'x'
    return func(x)

def square(n):
    return n * n

# Using the higher-order function
result = apply_function(square, 5)
print(result) # Output: 25
# Example of a function that returns another function
def make_multiplier(factor):
    # Returns a new function
    def multiplier(n):
        return n * factor
    return multiplier

# Creating a function to multiply by 3
times_three = make_multiplier(3)

# Using the returned function
result = times_three(4)
print(result) # Output: 12

Examples of built-in higher-order functions in Python: map, filter, reduce.