Home > Software design >  Nested lambdas working logic needs explanation
Nested lambdas working logic needs explanation

Time:08-11

I got code from here: https://news.ycombinator.com/item?id=25869596

>>> (
      lambda n: (lambda fact: fact(n, fact))(
          lambda n, inner: 1 if n == 0 else (n * inner(n - 1, inner))
      )
  )(5)
  120 

How does this work? I particularly cannot understand how inner gets value.

CodePudding user response:

This can be written as

def func(n):

    def func1(fact):
        return fact(n, fact)

    def func2(n, inner):
        return 1 if n == 0 else (n * inner(n - 1, inner))

    return func1(func2)

func(5)

inner is func2, or lambda n, inner: 1 if n == 0 else (n * inner(n - 1, inner)) in your example.

lambda fact: fact(n, fact) get the lambda as a parameter and call it recursively.

  • Related