带有局部状态的队列实现:
(define (make-queue)
(let ((front-ptr '())
(rear-ptr '())
)
(define (empty-queue?)
(eq? front-ptr '())
)
(define (front-queue)
(if (empty-queue?) (error "called with an empty queue")
(car front-ptr)
)
)
(define (print)
front-ptr
)
(define (insert-queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue?)
(set! front-ptr new-pair)
(set! rear-ptr new-pair)
(print))
(else (set-cdr! rear-ptr new-pair) (set! rear-ptr new-pair) (print)))
))
(define (delete-queue)
(cond ((empty-queue?) (display "called with an empty queue"))
(else (set! front-ptr (cdr front-ptr)) (print))
)
)
(define (dispatch m)
(cond ((eq? m 'empty?) (empty-queue?))
((eq? m 'front) (front-queue))
((eq? m 'insert) insert-queue)
((eq? m 'delete) (delete-queue))
(else (error "Unknown operation for queue" m))
)
)
dispatch)
)
使用的编译器是DrScheme,语言是R5RS。
使用这种消息分发的实现方式,封装性更强,扩展起来也比较容易。