Shuffled (Uniform Random) Range in Scala

Recently, I've found myself needing to iterate over a random permutation of a sequence of numbers. In Scala, the best way to get a sequence of numbers is to use a Range. My first intuition was to use a permutation method made available by SeqLike, however, this function creates an iterator over the distinct permutations of a sequence. Now while that might be useful under certain circumstances, it's not too useful here because I only needed to generate one permutation. The solution that I found was to use the shuffle function provided by Random in order to shuffle the iterator inside the Range.

Now, I took it a step further and created a small DSL (Domain-Specific Language) that adds shuffling directly to ranges in Scala. This allows me to do the following:

It's pretty straightforward to setup if you're even a little acquainted with implicit conversions. Here are the other two files that make it all work:


A commenter named Martin (Martin Odersky?) commented that since the "foreach" method takes a function of arity 1, we can use foreach println, which is just syntactic sugar for foreach (x => println(x)). Here is the example that he provided: