0

I got the following code:

g = lambda x: x+7
foo = lambda f: (lambda x: f(x+1)*2)
print( g(3), (foo(g))(3), (foo(foo(g))((3) )

Could I get an explanation on how (foo(foo(g))((3) works?

0

1 Answer 1

3

The first thing to remember is that lambdas are regular functions that:

  1. Don't automatically have names
  2. Can be used as expressions
  3. Must consist of a single expression
  4. Implicitly return the results of that expression

So you can always rewrite them as normal def functions with names if you're confused. For example, foo can become:

def foo(f):
    def foo_inner(x):
        return f(x + 1) * 2
    return foo_inner

So calling foo with any function (f) returns a new function which takes a numeric type, adds one to it, calls f with the value, and doubles the result.

All the rest of it is just tracing the multiple layers of wrapping here, which I'll leave to you; this isn't an interesting problem in general. In real code that uses factory functions like this, the intent and behavior is generally much more clear (because it's being done for a purpose, rather than as a brainteaser).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.