As a function language, scheme considers that every result of a function must be the same as a parameter in a transformation process. It is like the Function Y = x + 1. When x = 1 is, the value of Y is 2. No matter which day is the result. But for the real world, many things are changing. Therefore, set! is introduced in scheme! , Set-car! , Set-CDR! .
For a simple data structure such as stack, changes must be considered. Each time an element is pushed in or popped up, the stack must be changed. As for the stack representation, a natural idea is to use list, but there is a problem: because the scheme parameter transmission method is "value transfer ", in this way, an element cannot be added to an empty stack through a function. Therefore, I wrap the stack into an ordinal pair. The former points to a list, indicating the stack, and the latter is an integer representing the stack length.
(Define (make-stack)
(Cons' () 0 ))
Based on this definition, it is easy to write a function that determines whether the stack is empty:
(Define (empty-stack? Stack)
(= (CDR stack) 0 ))
How to obtain the top element of the stack? In this way, top-stack is available:
(Define (top-stack)
(If (empty-stack? Stack)
(Display "No element! ")
(Caar stack )))
Next is the major event: Press in and pop-up. It is not complicated. For the push-in operation, you only need to stick the new elements to the front of the stack, and then modify the stack top pointer (that is, (CAR stack )):
(Define (push-Stack! Stack item)
(Let (New-item (cons item (CAR stack ))))
(Set-car! Stack New-item)
(Set-CDR! Stack (+ (CDR stack) 1 ))))
For pop-up operations, make sure that there are elements in the stack. Modify the top pointer of the stack to return the pop-up elements ):
(Define (POP-Stack! Stack)
(If (empty-stack? Stack)
(Display "No element! ")
(Let (item (top-stack )))
(Set-car! Stack (cdar stack ))
(Set-CDR! Stack (-(CDR stack) 1 ))
ITEM )))