Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Design a structure stack that represents a stack of elements of some arbitrary t

ID: 3556002 • Letter: D

Question

Design a structure stack that represents a stack of elements of some arbitrary type. Include the functions: create(returns an empty stack), push(add an element to the top of the stack and return the resulting stack), pop(delete the top element and return the resulting stack), isEmpty (test whether a given stack is empty), and top (return the top element). Also include an exception EmptyStack to catch attempts to read or pop the top element of an empty stack.

Also design a suitable signature that will allow us to create from the stack a structure StringStack whose stacks have elements that are strings, and that omits the operation top.

Explanation / Answer

structure Stack :> sig type 'a stack exception EmptyStack val create : 'a stack val isEmpty : 'a stack -> bool val push : 'a -> 'a stack -> 'a stack val pop : 'a stack -> 'a stack val peek : 'a stack -> 'a end = struct type 'a stack = 'a list exception EmptyStack val create = nil fun isEmpty nil = true | isEmpty (x::xs) = false fun push v (s:'a stack) = v::s fun pop nil = raise EmptyStack | pop (x::xs) = xs fun peek nil = raise EmptyStack | peek (x::xs) = x end

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote