Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can lambda work with *args as its parameter? [duplicate]

Tags:

python

lambda

I am calculating a sum using lambda like this:

def my_func(*args):
    return reduce((lambda x, y: x + y), args)

my_func(1,2,3,4)

and its output is 10.

But I want a lambda function that takes random arguments and sums all of them. Suppose this is a lambda function:

add = lambda *args://code for adding all of args

someone should be able to call the add function as:

add(5)(10)          # it should output 15
add(1)(15)(20)(4)   # it should output 40

That is, one should be able to supply arbitrary number of parenthesis.

Is this possible in Python?

like image 926
Sony Khan Avatar asked Apr 26 '16 12:04

Sony Khan


1 Answers

This is not possible with lambda, but it is definitely possible to do this is Python.

To achieve this behaviour you can subclass int and override its __call__ method to return a new instance of the same class with updated value each time:

class Add(int):
    def __call__(self, val):
        return type(self)(self + val)

Demo:

>>> Add(5)(10)
15
>>> Add(5)(10)(15)
30
>>> Add(5)
5
# Can be used to perform other arithmetic operations as well
>>> Add(5)(10)(15) * 100
3000

If you want to support floats as well then subclass from float instead of int.

like image 183
Ashwini Chaudhary Avatar answered Oct 13 '22 09:10

Ashwini Chaudhary