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 can write a function in Haskell, that takes another function as argument, and returns the same function with it's arguments' order flipped. Can one do similiar thing in Python? For example,
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 possibly do this in Python?
Notice that when keyword arguments are used in the call, the order in which arguments are listed doesn't matter; Python matches by name, not position. The caller must supply values for spam and eggs , but they can be matched by position or name.
Python reversed() method returns an iterator that accesses the given sequence in the reverse order.
Argument Order MattersThe order or arguments supplied to a function matters. R has three ways that arguments supplied by you are matched to the formal arguments of the function definition: By complete name: i.e. you type main = "" and R matches main to the argument called main .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With