Scala.js中的Javascript生成器
目前,我使用Transcrypt从Python代码生成Javascript代码。通过这种方式,我可以用Python实现生成器,如:Scala.js中的Javascript生成器,javascript,python,scala,scala.js,transcrypt,Javascript,Python,Scala,Scala.js,Transcrypt,目前,我使用Transcrypt从Python代码生成Javascript代码。通过这种方式,我可以用Python实现生成器,如: def color(): colors = ["red", "blue", "yellow"] i = -1 while True: i += 1 if i >= colors.length: i = 0 reset = yield colors[i]
def color():
colors = ["red", "blue", "yellow"]
i = -1
while True:
i += 1
if i >= colors.length:
i = 0
reset = yield colors[i]
if reset:
i = -1
gen = color()
console.log(next(gen)) # red
console.log(gen.js_next(True).value) # red
console.log(next(gen)) # blue
console.log(next(gen)) # yellow
console.log(next(gen)) # red
将编译为Javascript,如:
var color = function* () {
var colors = list (['red', 'blue', 'yellow']);
var i = -(1);
while (true) {
i++;
if (i >= colors.length) {
var i = 0;
}
var reset = yield colors [i];
if (reset) {
var i = -(1);
}
}
};
var gen = color ();
console.log (py_next (gen));
console.log (gen.next (true).value);
console.log (py_next (gen));
console.log (py_next (gen));
console.log (py_next (gen));
但由于我也有Scala知识(以及我想在浏览器中实现的Scala应用程序),所以我希望使用Scala.js。但据我所知,这个生成器构造在Scala中是不可能的,相应的yield
关键字以不同的方式使用
Scala.js中是否可以使用生成器语法,或者如果需要,我是否必须使用Python和Transcrypt?我相信您要寻找的一般概念是Continuations。这本身就是一个相当大和复杂的话题——过去人们谈论得更多,但现在已经被更易于使用的异步库所取代。但是这个仍然存在,并且在网上讨论了很多地方——例如,或者。在我的脑海中,你可以看看如何翻译生成器代码你可以这样定义
color
:color=itertools.cycle([“red”,“blue”])
。我想充分利用生成器的可能性,比如向它发送值。这个例子太简单了。不幸的是,Scala.js中还没有任何生成器支持。我们正在努力(这很难)。目前还没有具体的计划来创建生成器。