-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.rkt
41 lines (33 loc) · 1 KB
/
stack.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#lang racket
(define (make-stack)
; store stack in list
(define stack '())
; whether or not the stack is empty
(define (empty?)
(null? stack))
; the number of items in the stack
(define (size)
(length stack))
; adds item to top of stack
(define (add! item)
(set! stack (cons item stack)))
; the item on top of stack
(define (peek)
(car stack))
; remove and return the item on top
(define (remove!)
(let ((removed (peek)))
(set! stack (cdr stack))
removed))
; allow methods to be accessed using (stack-instance 'method-name)
(define (dispatch method)
(cond ((equal? method 'empty?) empty?)
((equal? method 'size) size)
((equal? method 'add!) add!)
((equal? method 'peek) peek)
((equal? method 'remove!) remove!)
(else (error (string-append "Method "
(symbol->string method)
" doesn't exist")))))
dispatch)
(provide make-stack)