an oop question
Julieta Shem
jshem at yaxenu.org
Wed Nov 2 20:37:51 EDT 2022
Greg Ewing <greg.ewing at canterbury.ac.nz> writes:
> 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.
The code for computing the length of a Pair (which is really a linked
list) happens to be the same for computing the length of a Stack. My
class Pair has methods map, filter, reduce, ... Stacks could use them
too.
> 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.
That works too.
More information about the Python-list
mailing list