How can I “transform the remaining” algorithm into a functional style?

In my Scala code in my imperative style, I have an algorithm:

def myProcessor(val items: List) {
  var numProcessed = 0
  while(numProcessed < items.size) {
    val processedSoFar = items.size - numProcessed
    numProcessed += processNextBlockOfItems(items, processedSoFar)
  }
}

I would like to keep the functionality of "block processing", and not just "takeWhile" in the list of elements. How can I rewrite this in a functional style?

+4
source share
2 answers

So, it depends on what you consider more functional, but here is the version without "var"

  def myProcessorFunctional(items: List[Int]) {
    def myProcessorHelper(items: List[Int], numProcessed: Int) {
      if (numProcessed < items.size) {
        val processedSoFar = items.size - numProcessed
        myProcessorHelper(items,
            numProcessed + processNextBlockOfItems(items, processedSoFar))
      }
    }
    myProcessorHelper(items, 0)
  }

(making it an Ints list for simplicity only, it would be easy to get it to work with a shared list)

, , - , .

, , processNextBlockOfItems , . , ( ) . , , processNextBlockOfItems...

:

- , , processNextBlockOfItems , , , ( List, , ).

- :

  def myProcessorMoreFunctional(items: List[Int]) {
    if (!items.isEmpty) {
        myProcessorMoreFunctional(processNextBlockOfItems(items))
      }
  }
+1

, "" ""

@tailrec
def myProcessor(items: List[A], count: Int = 0): Int = items match{
  case Nil => count
  case x :: xs => 
    processNextBlockOfItems(items, count) 
    myProcessor(xs, count + 1)
}

, "SoFar" . "" :

@tailrec
def myProcessor(items: List[A], count: Int = 0): Int = items match{
  case Nil => count
  case x :: xs => 
    process(x) 
    myProcessor(xs, count + 1)
}

process "" List.

+5

Source: https://habr.com/ru/post/1530271/


All Articles