高校化学2924392 views
りんご209490 views
中学理科1630641 views
中学英語811710 views
雑学1473612 views
いろは3010814 views
世界の国564520 views
ヒストリア290598 views
高校生物551766 views
高校倫理1440106 views
Help
Tools
NewsSpreadsheetCalendarBookkeepingMarkdown TablesSlidesTier ListPen ToolIllustrationCrayonWatercolorPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchSwirl EffectLine ArtOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsRolling DiceCross SectionsMotion PathMechanicsWavesElectromagnetic WavesCapacitorsLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHOrganic Reaction MapPeriodic TableComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseMuscle ContractionHormones and HomeostasisRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic TheoryShogi StrategyPiano Rhythm Game

English

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

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