IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    scala里模拟javascript/python里的生成器的效果

    hongjiang发表于 2016-05-03 19:39:46
    love 0

    上一篇关于yield的字面含义,基本有答案了。对于python和javascript不太熟悉,这两个语言里yield都是配合生成器而使用的。比如下面这段 javascript 的例子从mozilla的网站上看到的,稍加改造:

    ➜  cat test.js
    
    function* foo() {
      var index = 0;
    
      while (index <= 2 ) {
        console.log("here" + index);
        yield index++;
      }
    }
    
    var it = foo();
    
    console.log("generator ready");
    
    console.log(it.next());
    console.log(it.next());
    console.log(it.next());
    

    它的输出结果是

    ➜  node test.js
    generator ready
    here0
    { value: 0, done: false }
    here1
    { value: 1, done: false }
    here2
    { value: 2, done: false }
    

    在Scala里yield并不等效于javascript/python里的效果,要等效的话,必须通过lazy, Stream等延迟计算特性来实现:

    ➜  cat Test.scala
    object Test {
      def main(args: Array[String]) {
    
        lazy val c = for( i <- (0 to 2).toStream ) yield {
          println("here" + i);
          i+1
        }
    
        println("ready")
    
        for( n <- c) {
          println(n)
        }
      }
    }   
    

    运行结果:

    ➜  scala Test.scala
    ready
    here0
    1
    here1
    2
    here2
    3       
    


沪ICP备19023445号-2号
友情链接