-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue-as-function.scm
48 lines (40 loc) · 1.22 KB
/
queue-as-function.scm
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
42
43
44
45
46
47
48
(define (make-queue)
(let ((front-ptr '())
(rear-ptr '()))
(define (empty-queue?)
(null? front-ptr))
(define (front-queue)
(if (empty-queue?)
(error "Queue is empty")
(car front-ptr)))
(define (set-front-ptr! item)
(set! front-ptr item))
(define (set-rear-ptr! item)
(set! rear-ptr item))
(define (insert-queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue?)
(set-front-ptr! new-pair)
(set-rear-ptr! new-pair))
(else (set-cdr! rear-ptr new-pair)
(set-rear-ptr! new-pair)))))
(define (delete-queue)
(cond ((empty-queue?)
(error "DELETE! called with an empty queue\n")
(else (set-front-ptr! (cdr front-ptr))))))
(define (print-queue)
(define (iter front)
(if (null? front)
(newline)
(begin (display (car front))
(display " ")
(iter (cdr front)))))
(iter front-ptr))
(define (dispatch m)
(cond ((eq? m 'empty-queue?) (empty-queue?))
((eq? m 'front-queue) (front-queue))
((eq? m 'insert-queue) insert-queue)
((eq? m 'delete-queue) (delete-queue))
((eq? m 'print-queue) (print-queue))
(else (error "Undefined operation on queue\n"))))
dispatch))