What is Self-Reference?

A self-referential function is one that returns itself.

Here's a simple example:

def f(x):
	"""
	A function that takes in an argument x, and prints it. 
	It returns a function that does the same functionality.
	>>> f(3)
	3
	<Function>
	"""
	print(x)
	return f
def print_delayed(x):
	"""
	A function that returns a function.
  It prints the value that was passed in the previous function.
	>>> one = print_delayed(1)
	>>> one
	<Function>
	>>> two = one(2)
	1
	>>> two
	<Function>
	>>> two(3)
	2
	<Function>
	"""
	def inner_print(y):
		print(x)
		return print_delayed(y)
	return inner_print

Let's Try A Question!

The second example we see above is a typical structure of self-recursion. Let's take another example to illustrate the "big idea" behind this.

<aside> โ“ Create a function print_delayed such that it returns a function โ€”ย which, when called, prints the previous value that was passed into it.

</aside>

Here's some insightful doctests.

>>> one = print_delayed(1)
>>> one
<function inner_print>
>>> two = one(2)
1
>>> two
<function inner_print>
>>> three = two(3)
2
>>> three
<function inner_print>

And here's a skeleton for you:

def print_delayed(x):
	"""
	A function that returns a function.
  It prints the value that was passed in the previous function.
	>>> one = print_delayed(1)
	>>> one
	<function inner_print>
	>>> two = one(2)
	1
	>>> two
	<function inner_print>
	>>> two(3)
	2
	<function inner_print>
	"""
	def inner_print(y):
		_____________________
		_____________________
	return ______________________

๐Ÿ›‘ Please give this question a shot before reading on! ๐Ÿ›‘


Working Towards an Answer