Le curry en Python à l'aide de functools.partial

PythonPythonBeginner
Pratiquer maintenant

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

💡 Ce tutoriel est traduit par l'IA à partir de la version anglaise. Pour voir la version originale, vous pouvez cliquer ici

Introduction

En programmation fonctionnelle, le curry est une technique consistant à transformer une fonction prenant plusieurs arguments en une séquence de fonctions prenant chacun un seul argument. En Python, on peut utiliser la fonction functools.partial() pour implémenter le curry.


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-13611{{"Le curry en Python à l'aide de functools.partial"}} python/tuples -.-> lab-13611{{"Le curry en Python à l'aide de functools.partial"}} python/function_definition -.-> lab-13611{{"Le curry en Python à l'aide de functools.partial"}} python/keyword_arguments -.-> lab-13611{{"Le curry en Python à l'aide de functools.partial"}} python/lambda_functions -.-> lab-13611{{"Le curry en Python à l'aide de functools.partial"}} python/importing_modules -.-> lab-13611{{"Le curry en Python à l'aide de functools.partial"}} python/using_packages -.-> lab-13611{{"Le curry en Python à l'aide de functools.partial"}} python/standard_libraries -.-> lab-13611{{"Le curry en Python à l'aide de functools.partial"}} end

Curry Function

Écrivez une fonction curry(fn, *args) qui curry une fonction donnée fn. La fonction devrait retourner une nouvelle fonction qui se comporte comme fn avec les arguments donnés, args, partiellement appliqués.

from functools import partial

def curry(fn, *args):
  return partial(fn, *args)
add = lambda x, y: x + y
add10 = curry(add, 10)
add10(20) ## 30

Summary

Dans ce défi, vous avez appris à implémenter une fonction curry à l'aide de functools.partial() en Python. La fonction curry vous permet d'appliquer partiellement des arguments à une fonction et de retourner une nouvelle fonction qui prend les arguments restants.