add heap sequencing fns to data/heap

This commit is contained in:
Stephen Chang 2012-10-27 21:09:02 -04:00
parent 4124c9a41b
commit 19f88c0f80
3 changed files with 61 additions and 8 deletions

View File

@ -160,13 +160,14 @@
(in-heap/consume! (heap-copy h)))
(define (in-heap/consume! h)
(lambda ()
(values (lambda () (heap-min h))
(lambda () (heap-remove-min! h) #t)
#t
(lambda (_) (> (heap-count h) 0))
(lambda _ #t)
(lambda _ #t))))
(make-do-sequence
(lambda ()
(values (lambda (_) (heap-min h))
(lambda (_) (heap-remove-min! h) #t)
#t
(lambda (_) (> (heap-count h) 0))
(lambda _ #t)
(lambda _ #t)))))
;; --------
@ -204,4 +205,7 @@
[heap->vector (-> heap? vector?)]
[heap-copy (-> heap? heap?)]
[heap-sort! (-> procedure? vector? void?)])
[heap-sort! (-> procedure? vector? void?)]
[in-heap (-> heap? sequence?)]
[in-heap/consume! (-> heap? sequence?)])

View File

@ -78,3 +78,34 @@ Makes a copy of heap @racket[h].
Sorts vector @racket[v] using the comparison function @racket[<=?].
}
@defproc[(in-heap/consume! [heap heap?]) sequence?]{
Returns a sequence equivalent to @racket[heap], maintaining the heap's ordering.
The heap is consumed in the process. Equivalent to repeated calling
@racket[heap-min], then @racket[heap-remove-min!].
@examples[#:eval the-eval
(define h (make-heap <=))
(heap-add-all! h '(50 40 10 20 30))
(for ([x (in-heap/consume! h)])
(displayln x))
(heap-count h)]
}
@defproc[(in-heap [heap heap?]) sequence?]{
Returns a sequence equivalent to @racket[heap], maintaining the heap's ordering.
Equivalent to @racket[in-heap/consume!] except the heap is copied first.
@examples[#:eval the-eval
(define h (make-heap <=))
(heap-add-all! h '(50 40 10 20 30))
(for ([x (in-heap h)])
(displayln x))
(heap-count h)]
}

View File

@ -67,3 +67,21 @@
(test-case "heap random dense"
(rand-test 20 100 50 100))
(test-equal? "in-heap"
(for/list ([x (in-heap (mkheap))]) x)
'(2 4 6 8 10))
(test-equal? "post in-heap count"
(let* ([h (mkheap)]
[lst (for/list ([x (in-heap h)]) x)])
(heap-count h))
(heap-count (mkheap)))
(test-equal? "in-heap/consume!"
(for/list ([x (in-heap/consume! (mkheap))]) x)
'(2 4 6 8 10))
(test-equal? "post in-heap/consume! count"
(let* ([h (mkheap)]
[lst (for/list ([x (in-heap/consume! h)]) x)])
(heap-count h))
0)