liveBook · Manning

Random-sample

As explained in Clojure: The Essential Reference

random-sample is a Clojure function that returns a sequence in which each input element is included independently according to a supplied probability.

random-sample randomly lets each element through with a supplied probability, returning a lazy sequence. With 0.5, each item has a 50% chance of appearing; the result is not guaranteed to contain half the input. section 8.3.3

Its contract is:

  • Call (random-sample prob coll) to sample a collection, or call (random-sample prob) to obtain an equivalent transducer. section 8.3.3 section 7.2
  • Treat probabilities below 0 as 0% and above 1 as 100%; a nonnumeric probability raises ClassCastException. section 8.3.3
  • Expect a variable output size: use another algorithm, such as reservoir sampling, when an exact sample size k is required. section 8.3.3

Sampling and transducer composition

(random-sample 0.5 (range 10)) ;; (1 2 7) (defn x-flip [n] (comp (take n) (random-sample 0.5))) (into [] (x-flip 10) (interleave (repeat "head") (repeat "tail"))) ;; ["head" "head" "tail" "head" "tail" "head" "tail" "tail"] section 8.3.3

Generating a fixed-length password

A low probability may produce too few items from a finite input. Repeating the alphabet with cycle and taking the desired length makes a compact password generator: (->> (cycle alphabet) (random-sample 0.01) (take 10) (apply str)) ;; "C3pu@Y6Xhm" section 8.3.3

Listing 8.12. → Random Selection
(random-sample
  ([prob])
  ([prob coll]))

Use the arity listing to distinguish direct collection sampling from the transducer form. section 8.3.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines arities, probability bounds, laziness, exceptions, and size limitations, but defers exact-size sampling to reservoir algorithms.
Examples
Demonstrates range sampling, coin-flip streams, repeated alphabets, password generation, and exact-size subset alternatives.
What it assumes
Assumes familiarity with Clojure collections, lazy sequences, transducers, and composition while demonstrating the probability contract.
What you can do after
Apply it via Clojure to produce probabilistic lazy sequences or transducers and recognize when exact-size sampling is needed.
How it connects
Connects random sampling with transducers, lazy sequences, cycle, take, and reservoir sampling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.