Python を使った関数合成

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

関数合成は、関数型プログラミングで使用される技術であり、2つ以上の関数を結合して新しい関数を形成します。Pythonでは、functools.reduce()関数を使用して、右から左への関数合成を行うことができます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/keyword_arguments("Keyword Arguments") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") subgraph Lab Skills python/comments -.-> lab-13607{{"Python を使った関数合成"}} python/tuples -.-> lab-13607{{"Python を使った関数合成"}} python/function_definition -.-> lab-13607{{"Python を使った関数合成"}} python/keyword_arguments -.-> lab-13607{{"Python を使った関数合成"}} python/lambda_functions -.-> lab-13607{{"Python を使った関数合成"}} python/importing_modules -.-> lab-13607{{"Python を使った関数合成"}} python/using_packages -.-> lab-13607{{"Python を使った関数合成"}} python/standard_libraries -.-> lab-13607{{"Python を使った関数合成"}} end

関数を合成する

compose(*fns) という名前の関数を書きます。この関数は、1つ以上の関数を引数として受け取り、入力関数を右から左に合成した結果である新しい関数を返します。最後の(最も右の)関数は1つ以上の引数を受け取ることができます。残りの関数は単項関数でなければなりません。

from functools import reduce

def compose(*fns):
  return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)
multiply_and_add_5(5, 2) ## 15

まとめ

このチャレンジでは、Pythonにおいて右から左への関数合成を行うためにfunctools.reduce()関数をどのように使用するかを学びました。また、compose()という名前の関数を書きました。この関数は、1つ以上の関数を引数として受け取り、入力関数を右から左に合成した結果である新しい関数を返します。