1

I'm trying to write a naive curried function in Python 2.7, but it seems like the inner lambda doesn't have an access to the parent lambda scope.

For simplicity, let's take this function:

add = lambda a: lambda b: a + b

The inner lambda's scope can't access the outer one (Python can't recognize a).

Is there a convenient way to make the outer scope accessible?

Ofir A.
  • 350
  • 2
  • 10

1 Answers1

2

This example seems to work for me in python 2.7.11

add = lambda a: lambda b: a + b
f = add(1)
print f(2)
3
print f(10)
11

More complicated examples might fall down though. A lambda function stores references to the variables in the enclosing scope, rather than their values. This might help with a more complicated problem: https://stackoverflow.com/a/938493/8131703

LangeHaare
  • 2,776
  • 2
  • 17
  • 25