Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flipping a function's argument order in Python

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?

like image 555
yasar Avatar asked Mar 24 '12 08:03

yasar


People also ask

Does the order of arguments matter 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.

What does reversed () do in Python?

Python reversed() method returns an iterator that accesses the given sequence in the reverse order.

Does the order of arguments in a function matter?

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 .


1 Answers

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)
like image 156
georg Avatar answered Sep 28 '22 18:09

georg