【问题标题】:Scala dropWhile predicate with iterators带有迭代器的 Scala dropWhile 谓词
【发布时间】:2018-09-13 00:14:40
【问题描述】:

我对 Scala 的 dropWhile 谓词与迭代器的使用有疑问。 这里我有一个简单的迭代器创建:

scala> val it = Iterator("a" , "number" , "of" , "words")
it: Iterator[String] = non-empty iterator

接下来我使用 dropWhile 谓词:

scala> it dropWhile ( _.length < 2 )
res52: Iterator[String] = non-empty iterator

接下来我在迭代器上执行下一条命令:

   scala> it next
   res53: String = of

现在注意迭代器下一个命令返回 "of" ,超过它应该是的。

如果我把同样的代码放在一个主函数中,下一个将返回“a”。 这相当令人困惑。有人可以解释一下吗?

【问题讨论】:

    标签: scala iterator main read-eval-print-loop


    【解决方案1】:

    来自docs

    特别重要的是要注意,除非另有说明, 在对迭代器调用方法后,永远不要使用迭代器。他们俩 最重要的例外也是唯一的抽象方法:next 和 有下一个。

    您需要将dropWhile 的结果分配给一个新变量并继续使用该变量,例如

    val remaining  = it dropWhile ( _.length < 2 )
    remaining.next
    

    【讨论】:

      【解决方案2】:

      Scala docsIterators 解释为

      An iterator is not a collection, but rather a way to access the elements of a collection one by one. The two basic operations on an iterator it are next and hasNext. A call to it.next() will return the next element of the iterator and advance the state of the iterator. Calling next again on the same iterator will then yield the element one beyond the one returned previously. If there are no more elements to return, a call to next will throw a NoSuchElementException.

      REPL

      当你在 REPL 中应用it dropWhile ( _.length &lt; 2 ) 时,它被分配给res52

      scala> it dropWhile ( _.length < 2 ) res52: Iterator[String] = non-empty iterator

      "a" , "number" 已被访问。所以应用it next 给你of 这是100% 正确

      主要

      main(),你一定做过

      val it = Iterator("a" , "number" , "of" , "words")
      it dropWhile ( _.length < 2 )
      print(it next)
      

      您可以清楚地看到 it dropWhile ( _.length &lt; 2 ) 没有像 REPL 中那样分配。因此,"a" , "number" 尚未被访问

      所以it nextmain() 中打印a

      希望解释对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        • 2011-06-20
        • 2020-05-24
        • 2015-07-22
        • 1970-01-01
        相关资源
        最近更新 更多