Search code examples
pythonstackjax

Reason to return updated stack along with top element from pop() method


This:

  def pop(self) -> tuple[Any, Stack]:
    """Pops from the stack, returning an (elem, updated stack) pair."""

What is the reason behind returning updated stack along with top element from pop() method?


Solution

  • From the docstring of the Stack class: "A bounded functional stack implementation."

    A functional implementation generally means that pure functions are used. The pop function implements two pure function properties:

    • The output does not change when called multiple times with the same input.
    • The function does not mutate the stack, ie it does not introduce side effects.

    This is why it must return a (mutated) copy of the input Stack instead of modifying it.