【问题标题】:How to construct such a functional-programming tool in Python?如何在 Python 中构建这样一个函数式编程工具?
【发布时间】:2012-07-20 06:09:09
【问题描述】:

我想要一个名为times() 的函数,以便制作:

times(func,2) 等同于lambda x:func(func(x))

times(func,5) 等价于lambda x:func(func(func(func(func(x)))))

Python中有这样的工具吗?如果我想自己写代码会是什么样子?

谢谢!

【问题讨论】:

    标签: python function recursion functional-programming


    【解决方案1】:

    我建议称它为power(),因为这实际上是函数的nth 次方。标准库中没有这种东西,但是你可以自己轻松实现:

    def power(f, n):
        def wrapped(x):
            for i in range(n):
                x = f(x)
            return x
        return wrapped
    

    【讨论】:

    • 如果可以的话,我会给这个+100。好优雅!
    • 我只是想知道是否有 recursive 而不是 iterative 方式来做到这一点..
    【解决方案2】:

    谢谢,斯文

    我找到了一种递归方式来做到这一点,但你的看起来更像 Python:

    def power(func, n):
        def lazy(x, i=n):
            return func(lazy(x, i-1)) if i > 0 else x
        return lazy    
    
    >>> power(lambda x:x*2,3)(9)
    72
    >>> power(lambda x:x*2,2)(9)
    36
    >>> power(lambda x:x*2,1)(9)
    18
    >>> power(lambda x:x*2,0)(9)
    9
    

    还有一种用装饰器实现的方式:

    def powerize(n):
        def wrapped(func):
            def newfunc(*args):
                return power(func,n)(*args)
            return newfunc
        return wrapped
    
    @powerize(3)
    def double_3(x):
        return x*2
    
    >>> double_3(8)
    64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2021-12-08
      • 2020-09-18
      • 1970-01-01
      相关资源
      最近更新 更多