Is there a more idiomatic way to get N random collection items in Clojure?

Im really doing this: (repeatedly n #(rand-nth (seq coll))) , but I suspect there might be a more idiomatic way for two reasons:

  • Ive found that theres is often a more concise and expressive alternative to using short anonymous functions, for example. partial
  • docstring for repeatedly says β€œpresumably with side effects,” meaning it is not intended to be used to create values

I suppose I can find a way to use reduce , but it seems that it would be difficult and less efficient, since I would have to process the entire collection, since reduce not lazy.

+4
source share
2 answers

A simple solution, but not optimal for large collections, might be:

 (take n (shuffle coll)) 

Has the "advantage" of non-repeating elements. You can also implement lazy-shuffle, but it will contain more code.

+4
source

I know that this is not quite what you are asking for, but if you are doing a large sample and statistical work, you might be interested in the Incanter ( [incanter "1.5.2"] ). Incanter provides a sample function that provides sample size and replacement options.

 (require '[incanter.stats :refer [sample]])) (sample [1 2 3 4 5 6 7] :size 5 :replacement false) ; => (1 5 6 2 7) 
+1
source

Source: https://habr.com/ru/post/1497820/


All Articles