Lambda evaluation

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Joshua Ginsberg

    #1

    Lambda evaluation

    So this part makes total sense to me:
    [color=blue][color=green][color=darkred]
    >>> d = {}
    >>> for x in [1,2,3]:[/color][/color][/color]
    .... d[x] = lambda y: y*x
    ....[color=blue][color=green][color=darkred]
    >>> d[1](3)[/color][/color][/color]
    9

    Because x in the lambda definition isn't evaluated until the lambda is
    executed, at which point x is 3.

    Is there a way to specifically hard code into that lambda definition the
    contemporary value of an external variable? In other words, is there a
    way to rewrite the line "d[x] = lambda y: y*x" so that it is always the
    case that d[1](3) = 3?

    Thanks!

    -jag

  • Steve M

    #2
    Re: Lambda evaluation

    Here's another one:
    [color=blue][color=green][color=darkred]
    >>> d = {}
    >>> for x in [1,2,3]:[/color][/color][/color]
    .... d[x] = (lambda z: lambda y: y * z) (x)
    ....[color=blue][color=green][color=darkred]
    >>> d[1](3)[/color][/color][/color]
    3[color=blue][color=green][color=darkred]
    >>> d[2](3)[/color][/color][/color]
    6

    Comment

    Working...