On 2/11/22 9:54 am, Julieta Shem wrote:
But we've left behind a more basic requirement --- the Stack
class wishes for all the methods already written in some class called
Pair,

Is that *really* what you want, though?

To my way of thinking, a Stack and a Pair are quite different
data structures, each having their own characteristic operations.

Things I want to be able to do with a Stack:
- Create an empty stack
- Push an item onto the top of the stack
- Pop an item off the top of the stack

Things I want to be able to do with a Pair:
- Create a pair containing two given objects
- Get the first item
- Get the second item

I don't see any overlap between these at the conceptual level.
Possibly I might want to use Pairs as part of the *implementation*
of a stack, but that doesn't mean that any Pair methods should
appear as Stack methods.

Here's how I might do this in a functional style using Python:

class Pair:
    def __init__(self, first, second):
        self._first = first
        self._second = second
    def first(self):
        return self._first
    def second(self):
        return self._second

class Stack:
    def __init__(self):
        self._data = None
    def push(self, item):
        result = Stack()
        result._data = Pair(item, self._data)
        return result
    def pop(self):
        rest = Stack()
        rest._data = self._data.second()
        return self._data.first(), rest

Note that neither Stack nor Pair inherits from the other.

--
Greg

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to