Best Functional Approach
- by dbyrne
I have some mutable scala code that I am trying to rewrite in a more functional style. It is a fairly intricate piece of code, so I am trying to refactor it in 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)
}
This didn't seem functional at all to me, since I still have side effects mixed throughout my code. My second thought was this:
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 a better solution to me, because at least I've isolated my functional value-generation code from the mutable value-processing code. However, this is much less memory efficient because I am generating a large list that I don't really need to store.
This leaves me with 3 choices:
Write a tail-recursive function, bite the bullet and refactor the value-processing code
Use a lazy list. This is not a memory sensitive app (although it is performance sensitive)
Come up with a new approach.
I guess what I really want is a lazily evaluated sequence where I can discard the values after I've processed them. Any suggestions?