Clojure iteration equivalent in scala?

The recursion is cool, but kind of low-level when you surround the library functions of a higher order. I am trying to avoid writing a recursive function to a process that depends on the last generated value.

I usually used a iteratefunction in Clojure over an “encrypted” list of the last value and current parameter. Is there an equivalent function in the Scala API?

Here is an abstract example attempt in some crazy pseudo-code:

Say what you have

  • Input List: Seq(1,2,3)
  • Some of the actions you perform with the last value and the next item in the list are:

    lastValue ^ 2 + nextInt(i)

and you want to copy all the generated values.

I am trying to 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)
}

- Fibonacci Haskell, , , , Clojure .

+5
3

, , scanLeft, , . , , :

val ls = Seq(1, 2, 3)
def gen(lastValue: Double, n: Int) = math.pow(lastValue, 2) + n

: scanLeft:

scala> ls.scanLeft(1.0)(gen)
res0: Seq[Double] = List(1.0, 2.0, 6.0, 39.0)

Apocalisp foldLeft, , scanLeft , .

0

, ? , iterate Clojure:

List.iterate(1, 5) { _ + 1 }
// res1: List[Int] = List(1, 2, 3, 4, 5)

, iterate List GenTraversableFactory.

, len - , , , , iterate Clojure.

Update:

- ! Stream iterate, :

(Stream.iterate(1) { _ * 2 } take 5).toList
// res1: List[Int] = List(1, 2, 4, 8, 16)
+6

The code you showed is basically equivalent to something like:

ls.foldLeft(List(1.0))((a, b) => gen(a.head, b) :: a).reverse
+3
source

All Articles