Better Functional Approach

I have some mutable scala code that I am trying to rewrite in a more functional style. This is a pretty complex piece of code, so I'm trying to reorganize it into pieces. My first thought was this:

def iterate(count:Int,d:MyComplexType) = {
  //Generate next value n
  //Process n causing some side effects
  return iterate(count - 1, n)
}

iterate(2000000,initialValue)

This did not seem functional to me, since I still have side effects mixed throughout my code. My second thought was the following:

def generateStream(d:MyComplexType):Stream[MyComplexType] = {
  //Generate next value n
  return Stream.cons(n, generateStream(n))
}

for (n <- generateStream(initialValue).take(2000000)) {
  //process n causing some side effects
}

This seemed like the best solution for me, because at least I isolated my functional value code from the mutable value processing code. However, it is much smaller than memory, because I am creating a large list that I really do not need to store.

This leaves me with 3 options:

  • Write a tail recursive function, bite the marker and refactor the value processing code
  • . , ( )
  • .

, , , , . ?

+3
2

, , . -!

Scala 2.8 Iterator.iterate . , , . , " " .

:

Iterator.iterate(initialState)(x => {
  // create a new state based upon state x
}).drop(2000000).next

, . 2000000 ( ), ( 2000000- ). 0 x = > x + 1, .

+6

, Range, , , Seq int 0 2000000 , , 2.7.

+3

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


All Articles