Flipping a function's argument order in Python

前端 未结 2 1607
被撕碎了的回忆
被撕碎了的回忆 2020-12-31 16:50

Nowadays, I am starting to learn haskell, and while I do it, I try to implement some of the ideas I have learned from it in Python. But, I found this one challenging. You ca

相关标签:
2条回答
  • 2020-12-31 17:12

    In a pure functional style:

    flip = lambda f: lambda *a: f(*reversed(a))
    
    def divide(a, b):
        return a / b
    
    print flip(divide)(3.0, 1.0)
    

    A bit more interesting example:

    unreplace = lambda s: flip(s.replace)
    
    replacements = ['abc', 'XYZ']
    a = 'abc123'
    b = a.replace(*replacements)
    print b
    print unreplace(b)(*replacements) # or just flip(b.replace)(*replacements)
    
    0 讨论(0)
  • 2020-12-31 17:21

    You can create a closure in Python using nested function definitions. This lets you create a new function that reverses the argument order and then calls the original function:

    >>> from functools import wraps
    >>> def flip(func):
            'Create a new function from the original with the arguments reversed'
            @wraps(func)
            def newfunc(*args):
                return func(*args[::-1])
            return newfunc
    
    >>> def divide(a, b):
            return a / b
    
    >>> new_divide = flip(divide)
    >>> new_divide(30.0, 10.0)
    0.3333333333333333
    
    0 讨论(0)
提交回复
热议问题