代码之家  ›  专栏  ›  技术社区  ›  Srinivas

理解流中的递归

  •  0
  • Srinivas  · 技术社区  · 6 年前

      val bigIntFromStream : Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: bigIntFromStream.zip(bigIntFromStream.tail).map{x =>
        println(s"stream = ${bigIntFromStream} + stream.tail = ${bigIntFromStream.tail} + zipped value = ${bigIntFromStream.zip(bigIntFromStream.tail)}")
        println(s"Calculating value for ${x}, {x._1} = ${x._1}, {x._2} = ${x._2}")
        x._1 + x._2}
    

    代码的输出如下

    0 1 stream = Stream(0, 1, ?) + stream.tail = Stream(1, ?) + zipped value = Stream((0,1), ?)
    
    Calculating value for (0,1), {x._1} = 0, {x._2} = 1
    1 stream = Stream(0, 1, 1, ?) + stream.tail = Stream(1, 1, ?) + zipped value = Stream((0,1), ?)
    
    Calculating value for (1,1), {x._1} = 1, {x._2} = 1
    2 stream = Stream(0, 1, 1, 2, ?) + stream.tail = Stream(1, 1, 2, ?) + zipped value = Stream((0,1), ?)
    
    Calculating value for (1,2), {x._1} = 1, {x._2} = 2
    3 stream = Stream(0, 1, 1, 2, 3, ?) + stream.tail = Stream(1, 1, 2, 3, ?) + zipped value = Stream((0,1), ?)
    
    Calculating value for (2,3), {x._1} = 2, {x._2} = 3
    5 stream = Stream(0, 1, 1, 2, 3, 5, ?) + stream.tail = Stream(1, 1, 2, 3, 5, ?) + zipped value = Stream((0,1), ?)
    
    Calculating value for (3,5), {x._1} = 3, {x._2} = 5
    

    我的问题是x如何得到实际值和尾部之间的最后一个zip值?如果我遗漏了什么,请告诉我

    2 回复  |  直到 6 年前
        1
  •  1
  •   jwvh    6 年前

    回想一下 Stream 一开始是作为一个单一的元素,承诺在需要的时候得到更多。即使所有元素都已完全定义,情况也是如此。

    val ns = Stream(1,2,3,4,5)
    //ns: scala.collection.immutable.Stream[Int] = Stream(1, ?)
    

    val paired = ns zip ns.tail
    //paired: scala.collection.immutable.Stream[(Int, Int)] = Stream((1,2), ?)
    // The rest are (2,3), (3,4) and (4,5), but they haven't been realized yet.
    

    另外,当你索引一个 这是一个线性运算。换句话说,如果你想 paired(3) 代码将逐步通过(“实现”) paired(0) ,然后 paired(1) paired(2) ,最后 成对(3) .

    溪流 您发布的内容基本上是:

    // This is concept, not code.
    Stream(a=0, b=1, c=a+b, d=b+c, e=c+d, ...)
    

    溪流

        2
  •  0
  •   Mansoor Baba Shaik    6 年前
    object Test extends App {
      var bigIntFromStream : Stream[BigInt] = Stream(0,1)
    
      def addItems(n: Int)(x: Stream[BigInt]): Unit = {
        if(n > 0){
          val lastIndex: Int = bigIntFromStream.indices.last
          bigIntFromStream ++= Stream(bigIntFromStream(lastIndex - 1) + bigIntFromStream(lastIndex))
          addItems(n-1)(bigIntFromStream)
        }
      }
    
      addItems(10)(bigIntFromStream)
    
      println(bigIntFromStream.mkString(","))
    }