Best Functional Approach

Posted by dbyrne on Stack Overflow See other posts from Stack Overflow or by dbyrne
Published on 2010-05-13T18:03:07Z Indexed on 2010/05/13 18:44 UTC
Read the original article Hit count: 216

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:

  1. Write a tail-recursive function, bite the bullet and refactor the value-processing code
  2. Use a lazy list. This is not a memory sensitive app (although it is performance sensitive)
  3. 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?

© Stack Overflow or respective owner

Related posts about scala

Related posts about functional-programming