|
| 1 | +#lang racket |
| 2 | +(define (make-queue) |
| 3 | + (let ((front-ptr '()) |
| 4 | + (rear-ptr '())) |
| 5 | + (define (empty-queue?) |
| 6 | + (null? front-ptr)) |
| 7 | + |
| 8 | + (define (insert-queue! item) |
| 9 | + (let ((new-pair (mcons item '()))) |
| 10 | + (cond ((empty-queue?) |
| 11 | + (set! front-ptr new-pair) |
| 12 | + (set! rear-ptr new-pair)) |
| 13 | + (else |
| 14 | + (set-mcdr! rear-ptr new-pair) |
| 15 | + (set! rear-ptr new-pair))))) |
| 16 | + |
| 17 | + (define (delete-queue!) |
| 18 | + (cond ((empty-queue?) |
| 19 | + (error "DELETE! called with an empty queue")) |
| 20 | + (else |
| 21 | + (set! front-ptr (mcdr front-ptr))))) |
| 22 | + |
| 23 | + (define (front-queue) |
| 24 | + (if (empty-queue?) |
| 25 | + (error "FRONT called with an empty queue") |
| 26 | + (mcar front-ptr))) |
| 27 | + |
| 28 | + (define (print-queue) |
| 29 | + (displayln front-ptr)) |
| 30 | + |
| 31 | + (define (dispatch m) |
| 32 | + (cond ((eq? m 'empty?) empty-queue?) |
| 33 | + ((eq? m 'front) front-queue) |
| 34 | + ((eq? m 'insert!)insert-queue!) |
| 35 | + ((eq? m 'delete!)delete-queue!) |
| 36 | + ((eq? m 'print)print-queue))) |
| 37 | + dispatch)) |
| 38 | + |
| 39 | +(module+ test |
| 40 | + (require rackunit) |
| 41 | + |
| 42 | + (test-case "Test for make-queue success" |
| 43 | + (define q (make-queue)) |
| 44 | + (check-true ((q 'empty?))) |
| 45 | + ((q 'insert!) 'a) |
| 46 | + (check-equal? (with-output-to-string (lambda () ((q 'print)))) "{a}\n") |
| 47 | + ((q 'insert!) 'b) |
| 48 | + (check-equal? (with-output-to-string (lambda () ((q 'print)))) "{a b}\n") |
| 49 | + (check-equal? ((q 'front)) 'a) |
| 50 | + ((q 'delete!)) |
| 51 | + (check-equal? (with-output-to-string (lambda () ((q 'print)))) "{b}\n") |
| 52 | + (check-equal? ((q 'front)) 'b) |
| 53 | + (check-false ((q 'empty?))) |
| 54 | + ) |
| 55 | + |
| 56 | + (test-case "Test for make-queue unhappy path" |
| 57 | + (define q (make-queue)) |
| 58 | + (check-exn (regexp "DELETE! called with an empty queue") (lambda () ((q 'delete!)))) |
| 59 | + (check-exn (regexp "FRONT called with an empty queue") (lambda () ((q 'front)))) |
| 60 | + ) |
| 61 | + |
| 62 | + ) |
0 commit comments