Reputation: 51839
I’m currrently doing this: (repeatedly n #(rand-nth (seq coll)))
but I suspect there might be a more idiomatic way, for 2 reasons:
partial
repeatedly
says “presumably with side effects”, implying that it’s not intended to be used to produce valuesI suppose I could figure out a way to use reduce
but that seems like it would be tricky and less efficient, as it would have to process the entire collection, since reduce
is not lazy.
Upvotes: 4
Views: 1048
Reputation: 4173
I know it's not exactly what you're asking - but if you're doing a lot of sampling and statistical work, you might be interested in Incanter ([incanter "1.5.2"]
).
Incanter provides the function sample
, which provides options for sample size, and replacement.
(require '[incanter.stats :refer [sample]]))
(sample [1 2 3 4 5 6 7] :size 5 :replacement false)
; => (1 5 6 2 7)
Upvotes: 1
Reputation: 1829
An easy solution but not optimal for big collections could be:
(take n (shuffle coll))
Has the "advantage" of not repeating elements. Also you could implement a lazy-shuffle but it will involve more code.
Upvotes: 7