Is it possible to implement a stack data structure using sets and set theory?

280 Views Asked by At

Full disclosure, I am not a math student but a software engineering student so my knowledge of math is somewhat weak.

For a homework assignment of mine this week, our teacher has challenged us to create a formal specification of the a stack data structure. This includes defining functions of a Stack such as push, pop, and top. We can use any formal languages or tools that we want. I was thinking of approaching problem using sets and set theory. I like this because Sets are something I feel mostly comfortable with.

I was thinking about creating something recursive. For example, a set inside of a set.

{ { ... }, Top-Element }

Where Top-Element would be the element retrieved when the function top is called, and the inner-set would be the rest of the stack. The problem with this approach is that sets have no ordering, so I can't just get the last element in a set.

Is this a viable way of implementing a stack using a set?

1

There are 1 best solutions below

1
On BEST ANSWER

Your definition is ambiguous if you allow for nested sets. For instance, $$ \{\{\{\{1\}\}\},\{\{1\}\}\} $$ could refer either to the stack whose top element is $\{1\}$ and whose "rest of the stack" has just the element $\{\{1\}\}$, OR it could refer to the stack whose top element is $\{\{\{1\}\}\}$ and whose "rest of the stack" has just the element $\{1\}$.

One fix is to use an ordered pair instead. That is, define your stack as the ordered pair consisting of the remaining stack in the first element, and the "top object" as the second element. If you use something like Kuratowski's definition, then you can encode this purely in terms of sets, if you wanted to do so.