8

Just for curiosity. Discovered Lambdas a few days ago. I was jus wondering if something like that can be done:

(Tried on the interpret but none of my tries seemed to work)

p = lambda x: (lambda x: x%2)/2

There's no explicit purpose. I just did'nt find a satisfactory answer. I may have misunderstood Lambdas.

Juan Gallostra
  • 181
  • 1
  • 1
  • 8

3 Answers3

12

You can use an inner lambda to return another function, based on the outer parameters:

mul = lambda x: (lambda y: y * x)
times4 = mul(4)
print times4(2)
Thomas Fenzl
  • 4,342
  • 1
  • 17
  • 25
7

You aren't actually calling the inner lambda:

p = lambda x: (lambda x: x%2)(x)/2

Note in Python 2 this example will always return 0 since the remainder from dividing by 2 will be either 0 or 1 and integer-dividing that result by 2 will result in a truncated 0.

jamylak
  • 128,818
  • 30
  • 231
  • 230
  • The example was just to ilustrate the idea. And missed the point about having to call both functions. – Juan Gallostra May 31 '13 at 12:35
  • @JuanGallostra Ah alright, just thought it was worth mentioning otherwise someone else would. I presumed the example was abritrary anyway – jamylak May 31 '13 at 12:36
1

(lambda x: x%2) is a function, and dividing a function by 2 doesn't make any sense. You probably want to call it and divide what the value it returned.

kirelagin
  • 13,248
  • 2
  • 42
  • 57