add in-queue
This commit is contained in:
parent
27b32464c5
commit
5f2d18c1f9
|
@ -1,5 +1,8 @@
|
|||
#lang racket/base
|
||||
|
||||
(require (for-syntax racket/base
|
||||
unstable/wrapc))
|
||||
|
||||
;; A Queue contains a linked list with mutable cdrs, holding two pointers
|
||||
;; to the head and the tail -- where items are pulled from the head and
|
||||
;; pushed on the tail. It is not thread safe: mutating a queue from
|
||||
|
@ -55,6 +58,28 @@
|
|||
count
|
||||
(loop (link-tail link) (add1 count)))))
|
||||
|
||||
(define (in-queue queue)
|
||||
(in-list (queue->list queue)))
|
||||
|
||||
(define-sequence-syntax in-queue*
|
||||
(lambda () #'in-queue)
|
||||
(lambda (stx)
|
||||
(syntax-case stx ()
|
||||
([(var) (in-queue* queue-expression)]
|
||||
(with-syntax ([queue-expression/c (wrap-expr/c #'queue? #'queue-expression
|
||||
#:macro #'in-queue*)])
|
||||
#'[(var)
|
||||
(:do-in ([(queue) queue-expression/c])
|
||||
(void) ;; handled by contract
|
||||
([link (queue-head queue)])
|
||||
link
|
||||
([(var) (link-value link)])
|
||||
#t
|
||||
#t
|
||||
((link-tail link)))]))
|
||||
([(var ...) (in-queue* queue-expression)]
|
||||
#f))))
|
||||
|
||||
;; --- contracts ---
|
||||
|
||||
(require racket/contract)
|
||||
|
@ -76,4 +101,4 @@
|
|||
[queue-length (-> queue/c integer?)]
|
||||
[queue->list (-> queue/c (listof any/c))])
|
||||
|
||||
(provide enqueue! dequeue!)
|
||||
(provide enqueue! dequeue! (rename-out [in-queue* in-queue]))
|
||||
|
|
|
@ -79,6 +79,13 @@ thread-unsafe way.
|
|||
(queue? 'not-a-queue)]
|
||||
}
|
||||
|
||||
@defproc[(in-queue [queue queue?])
|
||||
sequence?]{
|
||||
|
||||
Returns a sequence whose elements are the elements of
|
||||
@racket[queue].
|
||||
}
|
||||
|
||||
@deftogether[(
|
||||
@defthing[queue/c flat-contract?]
|
||||
@defthing[nonempty-queue/c flat-contract?]
|
||||
|
|
|
@ -65,6 +65,13 @@
|
|||
(check-equal? (dequeue! q) 2)
|
||||
(check-exn exn:fail? (lambda () (dequeue! q))))))
|
||||
(test-suite "queue misc"
|
||||
(test-case "queue as a sequence"
|
||||
(let ([queue (make-queue)])
|
||||
(enqueue! queue 1)
|
||||
(enqueue! queue 2)
|
||||
(enqueue! queue 3)
|
||||
(check-equal? '(1 2 3) (for/list ([item (in-queue queue)]) item)))
|
||||
(check-equal? '() (for/list ([item (in-queue (make-queue))]) item)))
|
||||
(test-case "queue to empty list"
|
||||
(let ([queue (make-queue)])
|
||||
(check-equal? (queue->list queue) '())))
|
||||
|
|
Loading…
Reference in New Issue
Block a user