sequence-sample: various comments from Eli.

This commit is contained in:
Vincent St-Amour 2016-01-05 20:33:08 -06:00
parent 1ce6a49f94
commit 4b266f1ff2
2 changed files with 8 additions and 7 deletions

View File

@ -966,8 +966,7 @@ the @tt{RtlGenRand} system function.
any/c]{
Returns a random element of the sequence. Like @racket[sequence-length], does
not terminate on infinite sequences, and extracts elements up to the returned
element.
not terminate on infinite sequences, and evaluates the entire sequence.
@history[#:added "6.4"]}
@ -978,12 +977,13 @@ element.
[#:replacement? replacement? any/c #t])
(listof any/c)]{
Returns a list of @racket[n] elements of @racket[seq], picked at random.
Returns a list of @racket[n] elements of @racket[seq], picked at random, listed
in any order.
If @racket[replacement?] is non-false, elements are drawn with replacement,
which allows for duplicates.
Like @racket[sequence-length], does not terminate on infinite sequences, and
extracts elements up to the returned element.
evaluates the entire sequence.
@history[#:added "6.4"]}

View File

@ -25,8 +25,9 @@
(define (random-sample seq n [prng (current-pseudo-random-generator)]
#:replacement? [replacement? #t])
;; doing reservoir sampling, to do a single pass over the sequence
;; (some sequences may not like multiple passes)
;; (some sequences may not like multiple passes, e.g., ports)
(cond
[(zero? n) '()]
[(not replacement?)
;; Based on: http://rosettacode.org/wiki/Knuth's_algorithm_S#Racket
(define not-there (gensym))
@ -41,7 +42,7 @@
(unless (for/and ([s (in-vector samples)])
(not (eq? s not-there)))
(raise-argument-error 'random-sample
"integer less than sequence length"
"integer less than or equal to sequence length"
n))
(vector->list samples)]
[else
@ -57,6 +58,6 @@
(vector-set! samples j elt)))]))
(unless samples
(raise-argument-error 'random-sample
"non-empty sequence"
"non-empty sequence for n>0"
seq))
(vector->list samples)]))