liveBook · Manning

Shuffle

As explained in Clojure: The Essential Reference

shuffle is a Clojure function that returns a vector containing a random permutation of the elements in a supported collection.

shuffle takes a collection and returns a vector containing a random permutation of its elements. It is useful when every element should appear once in randomized order rather than selecting one element repeatedly. section 8.3.2 section 8.3.1

The contract is straightforward, with important input restrictions:

  • Accepts most Clojure collections, but excludes maps, transients, native arrays, and nil. section 8.3.2
  • Returns a vector, regardless of the supported collection type supplied. section 8.3.2
  • Can raise ClassCastException for unsupported collection interfaces and NullPointerException for nil. section 8.3.2
  • Uses Fisher–Yates shuffling supplied through the Java JDK. section 8.3.2

Randomize hosts before round-robin use

(defn round-robin [f hosts] (let [hosts (shuffle hosts) idx (atom 0)] (fn [] (f (nth hosts @idx)) (reset! idx (mod (inc @idx) (count hosts)))))) (def hosts ["10.100.89.42" "10.100.86.57" "10.100.23.12"]) (def get-host (round-robin request hosts)) (get-host) ;; calling http://10.100.23.12/index.html section 8.3.2

Use rand-nth when one random element is needed; use shuffle when multiple sequential selections should avoid retrieving the same element twice. section 8.3.1

Listing 8.11. → Random Selection, Random Permutation, Collection Shuffle
(shuffle [coll])

Browse the concise function listing for shuffle. section 8.3.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines inputs, outputs, exceptions, and Fisher–Yates implementation, without detailing the algorithm’s internal steps.
Examples
Demonstrates randomized host ordering for round-robin requests and contrasts whole-collection permutation with single-element selection.
What you can do after
Apply it via Clojure’s shuffle function to randomize supported collections and distribute sequential choices.
How it connects
Connects shuffle to rand-nth, rand-int, and round-robin resource allocation.

Also explained in

Compare how 3 books explain shuffle →

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.