So i'm learning about RecursiveLists and our prof has given us a init for the recursivelist class
class RecursiveList:
# === Private Attributes ===
# _first:
# The first item in the list.
# _rest:
# A list containing the items that come after
# the first one.
_first: Optional[Any]
_rest: Optional[RecursiveList]
# === Representation Invariants ===
# _first is None if and only if _rest is None.
# This represents an empty list.
def __init__(self, items: list) -> None:
"""Initialize a new list containing the given items.
The first node in the list contains the first item in <items>.
"""
if items == []:
self._first = None
self._rest = None
else:
self._first = items[0]
self._rest = RecursiveList(items[1:])
now I want to mutate the list by inserting an item to the front of the list but I can't wrap my head around how to do so. I understand that self._rest stores the rest of the list recursively and also that I should move the value of self._first into self._rest, but how do I move an int and turn it so that the recursive function has the rest of them?
def insert_first(self, item: object) -> None:
"""Insert item at the front of this list.
This should work even if this list is empty.
"""
self._rest, using previous first element value asitem.RecursiveList, it is actually aLinked List(as @L3viathan noted). Lists can beLinked Listsand methods can berecursive, as any computer science document from the past several decades will support.