我理解Ruby和Python的收益率.Scala的收益率是多少?
是否有可能在Scala中实现与Python yield语句等效的东西,它会记住使用它的函数的本地状态,并在每次调用时"产生"下一个值?
我希望有这样的东西将递归函数转换为迭代器.有点像:
# this is python
def foo(i):
yield i
if i > 0:
for j in foo(i - 1):
yield j
for i in foo(5):
print i
Run Code Online (Sandbox Code Playgroud)
除此之外,foo可能更复杂并通过一些非循环对象图重现.
附加编辑: 让我添加一个更复杂的例子(但仍然很简单):我可以编写一个简单的递归函数来打印事物:
// this is Scala
def printClass(clazz:Class[_], indent:String=""): Unit = {
clazz match {
case null =>
case _ =>
println(indent + clazz)
printClass(clazz.getSuperclass, indent + " ")
for (c <- clazz.getInterfaces) {
printClass(c, indent + " ")
}
}
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,我希望有一个库,允许我轻松更改一些语句并使其作为迭代器工作:
// this is not …Run Code Online (Sandbox Code Playgroud) 如何yield return使用Scala continuation 实现C#?我希望能够以Iterator相同的风格编写Scala .这篇Scala新闻帖的评论中有一个刺,但它不起作用(尝试使用Scala 2.8.0测试版).一个相关问题的答案表明这是可能的,但是虽然我已经玩了一段时间的分隔延续,但我似乎无法完全理解如何做到这一点.
我是Scala的新手,并试图绕过我试图重现yield returnC#语句的延续.
在这篇文章之后,我写了以下代码:
package com.company.scalatest
import scala.util.continuations._;
object GenTest {
val gen = new Generator[Int] {
def produce = {
yieldValue(1)
yieldValue(2)
yieldValue(3)
yieldValue(42)
}
}
// Does not compile :(
// val gen2 = new Generator[Int] {
// def produce = {
// var ints = List(1, 2, 3, 42);
//
// ints.foreach((theInt) => yieldValue(theInt));
// }
// }
// But this works?
val gen3 = new Generator[Int] {
def produce = {
var ints …Run Code Online (Sandbox Code Playgroud) 我想实现一个惰性迭代器,它在每个调用中产生一个3级嵌套循环中的下一个元素.
scala中有类似于c#的这个片段:
foreach (int i in ...)
{
foreach (int j in ...)
{
foreach (int k in ...)
{
yield return do(i,j,k);
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢,Dudu