Is there a more idiomatic way to get N random elements of a collection in Clojure?
clojure, idioms
Solution
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.
Problem
I’m currrently doing this: `(repeatedly n #(rand-nth (seq coll)))` but I suspect there might be a more idiomatic way, for 2 reasons: - I’ve found that there’s frequently a more concise and expressive alternative to using short anonymous functions, e.g. `partial` - the docstring for `repeatedly` says “presumably with side effects”, implying that it’s not intended to be used to produce values I 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.