【问题标题】:Scala implementation of C#-like yield with "for"使用“for”实现类 C# 的 Scala 实现
【发布时间】:2011-03-17 19:49:17
【问题描述】:

我正在尝试使用各种 Scala 实现的类似 C# 的 yield return(即this one)和“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) {

据我了解,我必须将所有代码都设置为 () =&gt; Unit,而不是 () =&gt; Unit @with-annotations。我该怎么做?

这个问题好像很常见,但是我在网上没有找到任何提及。

【问题讨论】:

  • 也许我遗漏了一些东西,但该示例中的大括号似乎不匹配。你怎么能在那里调用生成?它在嵌套范围内。
  • 我通过移除一个额外的大括号解决了这两个问题。
  • 此问题与以下问题重复,提供了答案:stackoverflow.com/questions/8934226/…

标签: scala scala-2.8 yield continuations yield-return


【解决方案1】:

如果您使用链接示例中的 iterator 类型,您的 generate 方法是否可能需要具有以下返回类型,而不是您拥有的返回类型?

Unit @cps[Iteration[Vector[T]],Iteration[Vector[T]]]

恐怕我对这些东西没有太多经验,但它看起来很像您在 iterator 中调用的方法必须在注解上有两个(相同的)类型参数。

【讨论】:

  • scala-lang.org/docu/files/api/scala/util/continuations/… : type cps = cpsParam[A, A] 所以我认为 scala 团队已将 cps 重命名为 cpsParam 并添加了 type cps 即使我使用@cps[Iteration[Vector[T]], Iteration[Vector[T]]] 问题依旧
  • 哦,对不起!我只是根据我在那里看到的东西工作。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 2023-03-14
  • 2021-10-17
  • 1970-01-01
相关资源
最近更新 更多