Search code examples
scalarecursionelementyield

yield - using element stored previously in list [Scala]


I will give a simplified code to explain my question easily:

  • I have a user balance i.e. val balance = 10
  • I have a list of data to iterate through using for(elem <- dataList) yield (interest(elem, balance)).
    • In my case interest is a method which will perform calculations on the given arguments and return a number which will be: provided balance+the calculated interest.

How can I use this newly returned value for the next element in my data list in yield so I could keep up-to-date my balance for the next elements in the list?

i.e. for(elem <- dataList) yield (interest(elem, newBalanceFromPreviousYield))


Solution

  • I think, there is no easy way to use it just with yield. Your use-case reminds fold pattern, so, let's use it. We accumulate balance and use it in interest() invocation:

    dataList.foldLeft(List.empty[Int]) { (acc, elem) =>
      acc match {
        case Nil =>
          // if no balances accumulated yet, use default balance = 10
          List(interest(elem, balance))
        case all@newBalance :: _ =>
          // else use accumulated balance
          interest(elem, newBalance) :: all
      }
    }.reverse // we need to reverse result list due to :: usage