Repositioning function argument order in Python

I'm currently starting to learn haskell, and while I am doing this, I am trying to implement some of the ideas that I learned from this in Python. But I found it complicated. You can write a function in Haskell that takes another function as an argument and returns the same function as the argument. Is it possible to do something like this in Python? For instance,

def divide(a,b): return a / b new_divide = flip(divide) # new_divide is now a function that returns second argument divided by first argument 

Can you do it in Python?

+6
source share
2 answers

You can create closures in Python using nested function definitions. This allows you to create a new function that changes the order of the argument, 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 
+11
source

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 somewhat 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) 
+6
source

Source: https://habr.com/ru/post/911555/


All Articles