Lambda Expressions: basic-level questions

If you need help reviewing Lambda Expressions, take a look at these resources:

Each question has a "Toggle Solution" button -- click it to reveal that question's solution.

Conceptual Questions

Question 1

What are some differences between def statements and lambda expressions?

Some differences between lambdas and def statements include:

  • lambdas are expressions (they are a value), while defs are statements.
  • lambdas can only be one liners
  • lambdas are anonymous — they have no intrinsic names

Question 2

What are the intrinsic names of the following functions?

def cube(x):
    return x * x * x

square = lambda x: x * x

The first function has an intrinsic name of cube. The second function does not have an intrinsic name, since it is a lambda. Note that the intrinsic name is the name you should write in your environment diagram frames!

What would Python print?

Question 3

>>> lambda x: x * x
______
>>> g = lambda x: x**2'
>>> g(4)
______
>>> (lambda x, y: x * y)(4, 5)
______

Code-Writing questions

Question 4

Translate the following def statements into lambda expressions.

# 1
def square(x):
    return x * x

# 2
def compose(f, g):
    def h(x):
        return f(g(x))
    return h
# 1
square = lambda x: x * x

# 2
compose = lambda f, g: lambda x: f(g(x))

Question 5

Translate the following lambda expressions into def statements.

# 1
pow = lambda x, y: x**y

# 2
foo = lambda x: lambda y: lambda z: x + y * z
# 1
def pow(x, y):
    return x**y

# 2
def foo(x):
    def f(y):
        def g(z):
            return x + y * z
        return g
    return f

Environment Diagrams

Question 6

square = lambda x: x * x
higher = lambda f: lambda y: f(f(y))

higher(square)(5)

Question 7

a = (lambda f, a: f(a))(lambda b: b * b, 2)