Skip to content

Instantly share code, notes, and snippets.

@raymondtay
Created April 5, 2012 04:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raymondtay/2307977 to your computer and use it in GitHub Desktop.
Save raymondtay/2307977 to your computer and use it in GitHub Desktop.
don't repeat the wheel, use fold/foldLeft/foldRight
object TestAccS extends App {
def add(i: Int, j: Int) = i + j
def accS[A](acc: A, s: Stream[A], fn: (A,A) => A) : A = {
if ( s.isEmpty ) return acc
accS( fn(acc, s.head), s.tail, fn)
}
val iS = Stream.iterate(1, 100){_ + 1} // the unbound parameter's draws the value from the immediate closure i.e. 1
println("Sum of elements: " + accS(0, iS, add) )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment