Below function getRandomString
generates a random String from a List of characters :
def genRandomInt(lb: Int, ub: Int) = {
val rnd = new scala.util.Random
lb + rnd.nextInt(ub)
}
def getRandomString(validChars: List[Char]) = {
val size = validChars.size
val random = new scala.util.Random
val stringBuilder = new StringBuilder
val rnd = genRandomInt(0, size)
val sb = new StringBuilder
for (i <- 0 to size - 1) {
val rnd = genRandomInt(0, size)
sb.append(validChars(rnd))
}
sb.toString
} //> getRandomString: (validChars: List[Char])String
val rs = getRandomString(('a' to 'j').toList)
//> rs : String = aghdjjhjge
Is getRandomString
an example of a pure function as it does not modify state ?
No, because it does in fact modify state. new scala.util.Random
ultimately invokes new java.util.Random
, which accesses and modifies a static (i.e. global), mutable AtomicLong
called seedUniquifier
. And therefore if this method is called multiple times then the result will change.
This is a good example of how innocent-seeming methods can hide accesses to global mutable state, which would be forbidden in a stricter functional language like Haskell (though that approach comes with its own problems).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With