I can't do most parts of this question without peeking at the answer key, so I figured I could ask it here. Frankly, I've always had a problem understanding functions with no parameters, and whenever I see one, I think, "OH! they must mean "print" function!" When I'm actually overcomplicating things.

As for Exercise 5, I'm not understanding how to even evaluate the expressions. I feel like it's a simple question, but I can't compute an answer to any of them.

Exercise 4: A Fistful of Functions

For each of the following expressions, what must f be in order for the evaluation of the expression to succeed, without causing an error? Give a definition of f for each expression such that evaluating the expression will not cause an error.

f
f()
f(3)
f()()
f()(3)() 

Solution

f = 3
f = lambda: 3
f = lambda x: x
f = lambda: lambda: 3
f = lambda: lambda x: lambda: x

Exercise 5: For A Few Lambdas More

Find the value of the following three expressions, using the given values of t and s.

t = lambda f: lambda x: f(f(f(x)))
s = lambda x: x + 1

t(s)(0) # 1

t(t(s))(0) # 2

t(t)(s)(0) # 3

Solution

1.) 3

2.) 9

3.) 27

有帮助吗?

解决方案

For Exercise 4, you are given the following questions and answers.

Q: f

A: f = 3

This is essentially variable assignment.

Q: f()

A: f = lambda: 3

This is similar to a function that takes in no arguments and returns the value 3.

Q: f(3)

A: f = lambda x: x

This is similar to a function that takes in the argument x and returns the value x. So you are given the value 3 and a value of 3 is returned.

Q: f()()

A: f = lambda: lambda: 3

This is similar to a function that takes in no arguments and returns another function that again takes no arguments which will return the value 3.

Q: f()(3)()

A: f = lambda: lambda x: lambda: x

Like the previous example, this will return 3. You have function that takes in no arguments but returns another function that takes in the value x and returns another function that takes in no arguments but returns the value x.

By following the examples above, you can solve Exercise 5 in a similar fashion.

Additionally, Exercise 5 has been explained pretty well in the comments by ChrisP.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top