使用“for”实现类似于 C# 的收益的 Scala 实现
我正在尝试使用类似 C# 的收益率返回的各种 Scala 实现(即 thisone) 与 "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)
}
}
但是这段代码编译时出现错误:
error: no type parameters for method foreach: (f: (Int) => U)Unit exist so that it can be applied to arguments ((Int) => Unit @util.continuations.package.cps[ru.ispras.texterra.nlp.GHMMDisambiguator.Iteration[Vector[T]]])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : (Int) => Unit @util.continuations.package.cps[ru.ispras.texterra.nlp.GHMMDisambiguator.Iteration[Vector[T]]]
required: (Int) => ?U
for (i <- left to right) {
据我所知,我必须将 for 中的所有代码都设为 () 类型=>单位
,不是() =>;单元@with-annotations
。我怎样才能做到这一点?
这个问题似乎很常见,但是我在网上没有找到任何提及。
I'm trying to use various Scala implementations of C#-like yield return (i.e. this one) with "for" -constructions such as:
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)
}
}
But this code compiles with error:
error: no type parameters for method foreach: (f: (Int) => U)Unit exist so that it can be applied to arguments ((Int) => Unit @util.continuations.package.cps[ru.ispras.texterra.nlp.GHMMDisambiguator.Iteration[Vector[T]]])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : (Int) => Unit @util.continuations.package.cps[ru.ispras.texterra.nlp.GHMMDisambiguator.Iteration[Vector[T]]]
required: (Int) => ?U
for (i <- left to right) {
As I understand I have to make all code inside for to be type of () => Unit
, not of () => Unit @with-annotations
. How can I do that?
This problem seems to be very common, but I didn't found any mentions in the Internet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用链接示例中的迭代器类型,那么您的生成方法是否需要具有以下返回类型,而不是您那里的返回类型?
恐怕我对这些东西没有太多经验,但看起来很像您在迭代器中调用的方法必须在注释上有两个(相同的)类型参数。
If you're using the
iterator
type from the linked example, is it possible that yourgenerate
method needs to have the following return type rather than the one you have there?I'm afraid I haven't got much experience with this stuff but it looks a lot like the methods you call within
iterator
must have two (identical) type arguments on the annotation.