일급함수란 프로그래밍 언어에서 하나의 '값'으로 취급할 수 있음을 의미한다. 즉 함수가 변수에 할당되거나, 다른 함수의 인자로 전달되거나, 함수에서 반환될 수 있는 성질을 갖고 있는 것을 말한다. 이러한 개념은 함수를 마치 다른 데이터타입처럼 다룰 수 있게 해준다.
def greet(name):
return f"Hello, {name}!"
greet_func = greet # 함수를 변수에 할당
print(greet_func("World")) # 출력: "Hello, World!"
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
greeting = func("Hello")
print(greeting)
greet(shout) # 출력: "HELLO"
greet(whisper) # 출력: "hello"
def create_greeting_func(greeting):
def greet(name):
return f"{greeting}, {name}!"
return greet
hello_greet = create_greeting_func("Hello")
print(hello_greet("Alice")) # 출력: "Hello, Alice!"
func_list = [greet, shout, whisper]
print(func_list[0]("Alice")) # 출력: "Hello, Alice!"
print(func_list[1]("Alice")) # 출력: "ALICE"
일급 함수는 코드의 유연성을 높여주며, 함수형 프로그래밍을 구현하는 데 중요한 개념이다. 이 개념을 잘 활용하면, 코드를 보다 간결하고 재사용 가능하게 만들 수 있다.
def process_data(data, callback):
# 데이터 처리
result = data * 2
# 콜백 호출
callback(result)
def print_result(result):
print(f"Result is: {result}")
process_data(5, print_result) # 출력: "Result is: 10"
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
고위함수란 함수를 인자로 받거나 함수를 반환하는 함수다. 고위함수는 함수형 프로그래밍에서 핵심적인 개념으로, 다른 함수들을 새로운 함수를 생성하거나 함수를 조합하여 동작을 확장할 수 있다.
map(), filter(), sorted() 등이 이러한 방식으로 동작한다.def apply_function(func, value):
return func(value)
def square(x):
return x * x
print(apply_function(square, 5)) # 출력: 25
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
doubler = make_multiplier(2)
print(doubler(5)) # 출력: 10
이 예시에서 make_multiplier 함수는 인자로 받은 factor를 기반으로 곱셈을 수행하는 함수를 반환한다.
map(): 함수와 이터러블을 인자로 받아, 이터러블의 각 요소에 함수를 적용하여 새로운 이터러블을 반환한다.numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # 출력: [1, 4, 9, 16]
filter(): 함수와 이터러블을 인자로 받아, 이터러블의 각 요소에 대해 함수를 적용한 결과가 True인 요소들만 반환한다.numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # 출력: [2, 4, 6]
reduce(): 이터러블의 요소들을 누적적으로 하나의 값으로 축소할 때 사용된다. 이를 사용하려면 functools 모듈에서 reduce()를 임포트해야 한다.numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # 출력: [2, 4, 6]
sorted() : 이터러블을 정렬된 리스트로 반환한다. 이때 key인자에 함수를 전달하여 정렬 기준을 설정할 수 있다.words = ["banana", "apple", "cherry"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words) # 출력: ['apple', 'banana', 'cherry']
고위 함수는 코드를 더 모듈화 하고 재사용성을 높이는 데 매우 유용하다.
1. 데코레이터 : 고위 함수를 사용하여 데코레이터를 구현할 수 있다. 데코레이터는 다른 함수를 감싸서, 그 함수의 동작을 확장하거나 변경하는 역할을 한다.
def timer(func):
import time
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Executed in {end_time - start_time} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(2)
print("Function finished")
slow_function()
여기서 @timer 데코레이터는 slow_function 함수가 실행된 시간을 측정하고 출력한다.
def make_power(n):
def power(x):
return x ** n
return power
square = make_power(2)
print(square(3)) # 출력: 9
일급 함수와 고위 함수는 밀접한 관계가 있습니다. 일급 함수가 있기 때문에 고위 함수를 구현할 수 있는 것입니다. 즉, 파이썬이 함수를 일급 객체로 취급하기 때문에, 함수를 인자로 전달하거나 반환할 수 있는 고위 함수를 구현할 수 있다.
일급 함수와 고위 함수는 함수형 프로그래밍(Functional Programming) 패러다임의 핵심 요소입니다. 함수형 프로그래밍에서는 함수를 일급 객체로 취급하고, 고차 함수를 활용하여 프로그램의 로직을 구성합니다. 이로 인해 코드의 재사용성과 유연성이 크게 향상된다.