3
\$\begingroup\$

In order to learn both scala and functional programming, I've been rewriting the projects from my introductory CS class in scala. One of the projects was a plinko game, where the user picks a slot to drop a token into and then the path that the token took and the money won from the end slot is printed to the console. The number of slots is constrained and so as the token falls row by row it can never be less than 0 or greater than 8.

I opted to use a stream to calculate the path, but I feel like the way that I am determining whether or not the token is within the constraints isn't really representative of functional programming because I know that generally vals are preferred to vars. What is a better way to write this in a functional style? In general, is there a way I should think about keeping track of things like this that is more in keeping with a functional programming style?

def getPath(prevSlot: Double): Stream[Double] = {
  var left = Random.nextBoolean
  if (prevSlot <= 0.0) {
    left = false
  }
  else if (prevSlot >= 8.0) {
    left = true
  }    

  if (left) { 
    prevSlot #:: getPath(prevSlot - 0.5) 
  }
  else {
    prevSlot #:: getPath(prevSlot + 0.5)
  }
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

In Scala the if-else pattern is an expression, which means we can use it to return a value (similar to Java's or C++'s ternary operator). You don't have to change much in order to take advantage of this:

def getPath(prevSlot: Double): Stream[Double] = {
  val left = 
    if (prevSlot <= 0.0) false
    else if (prevSlot >= 8.0) true
    else Random.nextBoolean

  if (left) prevSlot #:: getPath(prevSlot - 0.5)
  else prevSlot #:: getPath(prevSlot + 0.5)
}

And then of course you could get a readout of your path with the following:

getPath(4.0).take(13).toList.foreach(println)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.