[英]Is there a more idiomatic way to get N random elements of a collection in Clojure?
I'm currrently doing this: (repeatedly n #(rand-nth (seq coll)))
but I suspect there might be a more idiomatic way, for 2 reasons: 我正在做这个:(
(repeatedly n #(rand-nth (seq coll)))
但我怀疑可能有更惯用的方式,原因有两个:
partial
partial
函数)通常会有更简洁和富有表现力的替代方法 repeatedly
says “presumably with side effects”, implying that it's not intended to be used to produce values repeatedly
说“大概有副作用”,暗示它不打算用来产生价值 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. 我想我可以找到一种方法来使用
reduce
但这看起来会很棘手且效率低下,因为它必须处理整个集合,因为reduce
不是懒惰的。
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.
你也可以实现一个懒惰的shuffle,但它会涉及更多的代码。
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(
[incanter "1.5.2"]
)感兴趣。 Incanter provides the function sample
, which provides options for sample size, and replacement. Incanter提供功能
sample
,提供样本大小和替换选项。
(require '[incanter.stats :refer [sample]]))
(sample [1 2 3 4 5 6 7] :size 5 :replacement false)
; => (1 5 6 2 7)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.