Recursion is cool, but sort of low level when you are surrounding by higher order library functions. I am trying to avoid writing a recursive function for a process that depends on the last value generated.
I would usually use iterate function in Clojure over a “zipped” list of last value and current parameter. Is there an equivalent function in Scala’s collection API?
Here is an attempt at an abstract example in some crazy pseudo code:
Say you have
- An input list:
Seq(1,2,3) -
Some action you perform to the last value generated and the next item in the list:
lastValue ^ 2 + nextInt(i)
and you want to accumulate all the values generated.
I am trying avoid writing something similar to:
def f(ls:Seq[Int]):Seq[Float] = {
def g(pos:Int, lastGen:Float):Seq[Float] = {
val v = gen(lastGen, ls(pos))
if( end(v) )
Seq(v)
else
Seq(v) ++ g(pos+1, v)
}
f(0, 1)
}
I have seen something similar in defining a lazy stream version of Fibonacci in Haskell, so hypothetically I could use a lazy stream that referred to itself, but that is harder to wrap my brain around than Clojure’s iterate.
It sounds like the higher order function you want is
scanLeft, which is like a fold that remembers its intermediate steps. For example, say you have the following:Then you can combine them like this with
scanLeft:This is more or less equivalent to Apocalisp’s formulation with
foldLeft, except thatscanLefttakes care of holding on to the intermediate values for you.