Scheme Data Structure-Stack

Source: Internet
Author: User

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 )))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.