It is possible to increase a number object like int
within a lambda function?
Imagine having a peek function like:
def _peek(cb, iter):
for i in iter:
cb(i)
How can I peek and add these values to a sum like in this following simple example:
numbers = (1, 2, 3)
s = 0
# Doesn't work, because __add__ doesn't add inline
_peek(s.__add__, numbers)
# Doesn't work, because s is outside of scope (syntax error)
_peek(lambda x: s += x, numbers)
# Does work, but requires an additional function
def _sum(var):
nonlocal s
s += var
_peek(_sum, numbers)
# Does work, but reduces numbers
sum = reduce(lambda x, y: x+y, numbers)
Now this is a real world example:
@dataclass
class Vote:
count = 0
def add_count(self, count: int):
self.count += count
vote = Vote()
# Doesn't work work
_peek(lambda x: vote.count += x, map(lambda x: x['count'], data))
# Does work, but requires additional function
_peek(vote.add_count, map(lambda x: x['count'], data))
In Java, I can write easily:
@Test
public void test_numbers() {
class Vote {
int count = 0;
}
var vote = new Vote();
var count = Stream.of(1,2,3).peek(i -> vote.count+=i).filter(i -> i > 1).count();
assert vote.count == 6;
assert count == 2;
}