Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a pure function in Scala

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 ?

like image 393
blue-sky Avatar asked Dec 19 '14 15:12

blue-sky


1 Answers

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).

like image 168
lmm Avatar answered Oct 30 '22 09:10

lmm