Home > other >  scala: avoid a var while iterating and accumulating in a functional manner (no vars)
scala: avoid a var while iterating and accumulating in a functional manner (no vars)

Time:06-12

I need help to find the right Scala approach that will make this code more functional and less mutable.

  def findMinTime(str: String, timeByCar: Int): Int = {
    var myTime = timeByCar
    var minTime = timeByCar
    str.reverse.foreach { l =>
      if (l == 'A') myTime  = 3 else myTime -= 2
      if (myTime < minTime) minTime = myTime
    }
    minTime
  }

CodePudding user response:

Here's a solution using foldLeft. We store the two variables we need to modify after each character (myTime and minTime) in a tuple as the accumulator.

def findMinTime(str: String, timeByCar: Int): Int = {
  val (myTime, minTime) = str.reverse.foldLeft((timeByCar, timeByCar)) {
    case ((myTime, minTime), l) =>
      val newTime = if (l == 'A') myTime   3 else myTime - 2
      (newTime, newTime min minTime)
  }
  minTime
}
  • Related