Recursive List
tags
#cs
Definition
A recursive definition of a list:
- The empty list
[]is a list - If
xis a value andris a list, then we can construct a new listlstwhose first element isxand whose other elements are the elements ofr
Visualisation:
[1, 2, 3, 4] ==
([1] +
([2] +
([3] +
([4] + [])))
Python implementation
class RecursiveList:
"""A recursive implementation of the List ADT.
Representation Invariants:
- (self._first is None) == (self._rest is None)
"""
# Private Instance Attributes:
# - _first: The first item in this list, or None if this list is empty.
# - _rest: A list containing the items in this list that come after the first one,
# or None if this list is empty.
_first: Optional[Any]
_rest: Optional[RecursiveList]
def __init__(self, first: Optional[Any], rest: Optional[RecursiveList]) -> None:
"""Initialize a new recursive list."""
self._first = first
self._rest = rest
Optionalis used because there doesn't necessarily have to be a_firstelement (empty list)
Operations
List Sum
Recursive definition: $$ \text{sum(lst)} = \begin{cases} 0, & \text{lst is empty} \\ \text{(first of lst)} + \text{sum of lst}, & \text{lst is non-empty} \end{cases} $$
Python implementation:
class RecursiveList:
def sum(self) -> int:
"""Return the sum of the elements in this list.
Preconditions:
- every element in this list is an int
"""
if self._first is None: # Base case: this list is empty
return 0
else: # Recursive case: this list is non-empty
return self._first + self._rest.sum()