我编辑了下面的代码,因为我相信我在问题之上错误地组合了 IterV 对象iter.next
。
我正在Iteratee
scalaz 中进行试验,我想知道为什么以下方法不起作用。这是我所拥有的:
import scalaz._
import Scalaz._
import IterV._
implicit val iteratorEnumerator = new Enumerator[Iterator] {
def apply[E,A](iter: Iterator[E], i: IterV[E,A]): IterV[E,A] =
if (iter.isEmpty) i
else i.fold(done = (acc,input) => i,
cont = k => apply(iter, k(El(iter.next))))
}
/* probably incorrect
val iter = Iterator(1,2,3)
println("peek(iter) " + peek(iter).run)
println("peek(iter) " + peek(iter).run)
*/
def peekpeek[E]: IterV[E, (Option[E],Option[E])] =
for (a <- peek; b <- peek) yield (a,b)
def peekheadpeek[E]: IterV[E, (Option[E],Option[E],Option[E])] =
for (a <- peek; b <- head; c <- peek) yield (a,b,c)
peekpeek(Iterator(1,2,3,4)).run
peekheadpeek(Iterator(1,2,3,4)).run
这将返回:
res0: (Option[Int], Option[Int]) = (Some(1),Some(2))
res1: (Option[Int], Option[Int], Option[Int]) = (Some(1),Some(2),Some(3))
我期待的地方(Some(1),Some(1))
和(Some(1),Some(1),Some(2))
。
我怀疑这与iter.next
副作用有关。处理它的最佳方法是什么?
作为比较,这直接取自 scalaz网站的源代码示例可以正常工作:
implicit val StreamEnumerator = new Enumerator[Stream] {
def apply[E, A](e: Stream[E], i: IterV[E, A]): IterV[E, A] = e match {
case Stream() => i
case x #:: xs => i.fold(done = (_, _) => i,
cont = k => apply(xs, k(El(x))))
}
}