实现从左到右的函数组合

Beginner

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

简介

函数组合是函数式编程中用于将两个或多个函数组合以创建新函数的一种技术。在 Python 中,我们可以使用 functools 模块中的 compose 函数来执行函数组合。但是,compose 函数执行的是从右到左的函数组合,这可能并不适用于所有用例。在这个挑战中,你将实现一个执行从左到右函数组合的函数。

反向组合函数

编写一个函数 compose_right,它接受一个或多个函数作为参数,并返回一个执行从左到右函数组合的新函数。第一个(最左边的)函数可以接受一个或多个参数;其余函数必须是一元函数。

你的实现应该使用 functools 模块中的 reduce 函数来执行从左到右的函数组合。

from functools import reduce

def compose_right(*fns):
  ## 你的代码写在这里
from functools import reduce

def compose_right(*fns):
  return reduce(lambda f, g: lambda *args: g(f(*args)), fns)
add = lambda x, y: x + y
square = lambda x: x * x
add_and_square = compose_right(add, square)
add_and_square(1, 2) ## 9

总结

在这个挑战中,你实现了一个执行从左到右函数组合的函数 compose_right。你使用了 functools 模块中的 reduce 函数来执行从左到右的函数组合。