You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Two of the most important concepts in functional programming are first-class functions and higher-order functions. Understanding these is essential for A-Level Computer Science and forms the basis of many functional programming techniques.
A language has first-class functions (also called first-class objects or first-class citizens) if functions can be treated like any other value. Specifically, functions can be:
# 1. Assigning a function to a variable
def greet(name):
return f"Hello, {name}!"
say_hello = greet # Assign function to variable
print(say_hello("Alice")) # Output: Hello, Alice!
# 2. Passing a function as an argument
def apply(func, value):
return func(value)
result = apply(greet, "Bob")
print(result) # Output: Hello, Bob!
# 3. Returning a function from a function
def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # Output: 10
print(triple(5)) # Output: 15
# 4. Storing functions in a list
operations = [double, triple]
for op in operations:
print(op(4)) # Outputs: 8, then 12
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.