如何yield return使用Scala continuation 实现C#?我希望能够以Iterator相同的风格编写Scala .这篇Scala新闻帖的评论中有一个刺,但它不起作用(尝试使用Scala 2.8.0测试版).一个相关问题的答案表明这是可能的,但是虽然我已经玩了一段时间的分隔延续,但我似乎无法完全理解如何做到这一点.
我是Scala的新手,据我所知,Scala中的收益与C#中的收益不同,它更像是选择.
Scala有类似于C#的收益吗?C#的收益很好,因为它使编写迭代器变得非常容易.
更新:这是来自C#的伪代码示例,我希望能够在Scala中实现:
public class Graph<T> {
public IEnumerable<T> BreadthFirstIterator() {
List<T> currentLevel = new List<T>();
currentLevel.add(_root);
while ( currentLevel.count > 0 ) {
List<T> nextLevel = new List<T>();
foreach( var node in currentLevel ) {
yield return node;
nextLevel.addRange( node.Children );
}
currentLevel = nextLevel;
}
}
}
Run Code Online (Sandbox Code Playgroud)
此代码实现了图的迭代广度优先遍历,使用yield,它返回一个迭代器,以便调用者可以使用常规for循环遍历图,例如:
graph.BreadthFirstIterator().foreach( n => Console.WriteLine( n ) );
Run Code Online (Sandbox Code Playgroud)
在C#中,yield只是语法糖,可以很容易地编写迭代器(IEnumerable<T>在.Net中,类似于IterableJava).作为迭代器,它的评估很懒散.
更新II:我可能在这里错了,但我认为C#中的整个收益点是你不必编写更高阶函数.例如,你可以编写一个常规for循环或使用像select/ map/ filter/ 这样的方法,where而不是传入一个函数,然后遍历序列.
如graph.iterator().foreach(n => println(n))代替graph.iterator( …
我正在尝试使用各种Scala实现的C#类似的yield return(即这一个)和"for" - 这样的构造:
private def permutations[T](s: Vector[T]) = {
def swap(i: Int, j: Int) {
val tmp = s(i)
s.set(i, s.get(j))
s.set(j, tmp)
}
iterator[Vector[T]] {
def generate(left: Int, right: Int): Unit @cps[Iteration[Vector[T]]] = {
if (left >= right)
yieldValue(s)
else {
generate(left, right)
for (i <- left to right) {
swap(left, i)
generate(left+1, right)
swap(left, i)
}
}
}
generate(0, s.size-1)
}
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码编译错误:
error: no type parameters for method foreach: (f: (Int) => U)Unit exist …Run Code Online (Sandbox Code Playgroud)