Python で関数を合成する(compose)

関数の合成(compose)は、複数の関数を組み合わせて新しい関数を作る手法です。Python には組み込みの compose 関数はありませんが、簡単に実装できます。

基本的な実装

2 つの関数を合成する例です。

def compose(f, g):
    return lambda x: f(g(x))

def add_one(x):
    return x + 1

def double(x):
    return x * 2

add_then_double = compose(double, add_one)
print(add_then_double(5))  # 12  (5+1=6, 6*2=12)

compose(f, g) は「まず g を適用し、その結果に f を適用する」関数を返します。数学の記法 f ∘ g と同じ順序です。

複数の関数を合成する

functools.reduce を使って任意個の関数を合成できます。

from functools import reduce

def compose(*funcs):
    return reduce(lambda f, g: lambda x: f(g(x)), funcs)

def add_one(x):
    return x + 1

def double(x):
    return x * 2

def square(x):
    return x ** 2

pipeline = compose(square, double, add_one)
print(pipeline(3))  # 64  (3+1=4, 4*2=8, 8**2=64)

パイプライン形式

右から左への適用が直感的でない場合は、左から右へ適用する pipe を作ることもできます。

def pipe(*funcs):
    return reduce(lambda f, g: lambda x: g(f(x)), funcs)

pipeline = pipe(add_one, double, square)
print(pipeline(3))  # 64

関数の合成を活用すると、データ変換の流れを宣言的に記述でき、各ステップを独立してテストしやすくなります。