1

想象一下有三个函数,它们都接受并返回相同类型的参数。

通常我们可以写成fun3(fun2(fun1(args)),这可以说是一个序列函数按顺序作用于参数,类似于一种高阶函数“map”。

你知道在 Mathematica 中,我们可以把它写成fun3@fun2@fun1@args.

现在的问题是,我们是否可以在不修改其定义的情况下将 fun3@fun2@fun1 集成为另一个 fun,因此fun(args)可以替换fun3(fun2(fun1(args)),这样看起来更优雅简洁。

4

3 回答 3

2
def merge_steps(*fun_list):
    def fun(arg):
        result = arg
        for f in fun_list:
            result = f(result)
        return result

    return fun


def plus_one(arg):
    return arg + 1


def double_it(arg):
    return arg ** 2


def power_ten(arg):
    return arg ** 10


combine1 = merge_steps(power_ten, plus_one, double_it)
combine2 = merge_steps(plus_one, power_ten, double_it)

combine1(3) 
> 3486902500

或使用 lambda:

steps = [power_ten, plus_one, double_it]

reduce(lambda a, f: f(a), steps, 3)
> 3486902500
于 2020-06-18T11:40:00.570 回答
1

I think you can use Function Recursion in python to do this.

def function(args, times):
    print(f"{times} Times - {args}")
    if times > 0 : 
        function(args,times - 1)

function("test", 2)

Note: I just add times argument to not generate infinite loop.

于 2020-06-18T10:44:22.577 回答
1

我不确定我是否理解您的问题,但是您是在谈论这些方面的功能组合吗?

# Some single-argument functions to experiment with.

def double(x):
    return 2 * x

def reciprocal(x):
    return 1 / x

# Returns a new function that will execute multiple single-argument functions in order.

def compose(*funcs):
    def g(x):
        for f in funcs:
            x = f(x)
        return x
    return g

# Demo.

double_recip_abs = compose(double, reciprocal, abs)
print(double_recip_abs(-2))   # 0.25
print(double_recip_abs(.1))   # 5.0
于 2020-06-18T10:58:43.790 回答