来自scala Iterator的scalaz Iteratees
发布时间:2020-12-16 09:05:09 所属栏目:安全 来源:网络整理
导读:我编辑了下面的代码,因为我认为我在iter.next问题之上错误地组合了IterV对象. 我正在尝试使用scalaz中的Iteratee,我想知道为什么以下不起作用.这是我有的: import scalaz._import Scalaz._import IterV._implicit val iteratorEnumerator = new Enumerator[
我编辑了下面的代码,因为我认为我在iter.next问题之上错误地组合了IterV对象.
我正在尝试使用scalaz中的Iteratee,我想知道为什么以下不起作用.这是我有的: 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])] = for (a <- peek; b <- head; c <- peek) yield (a,b,c) peekpeek(Iterator(1,3,4)).run peekheadpeek(Iterator(1,4)).run 返回: res0: (Option[Int],Option[Int]) = (Some(1),Some(2)) res1: (Option[Int],Option[Int],Some(2),Some(3)) 我期待的地方(Some(1),Some(1))和(Some(1),Some(1),Some(2)). 我怀疑这与iter.next的副作用有关.处理这个问题的最佳方法是什么? 为了比较,this直接从scalaz web site的源代码示例中正常工作: implicit val StreamEnumerator = new Enumerator[Stream] { def apply[E,A](e: Stream[E],A] = e match { case Stream() => i case x #:: xs => i.fold(done = (_,_) => i,cont = k => apply(xs,k(El(x)))) } } 解决方法
我想我想出来了.这似乎主要是由于El使用了一个by name参数,它重新计算iter.next – 以及我最初用两个不同的peek(iter).run错误地调用计算.我重新编写了枚举器,首先将iter.next分配给val(并且在该过程中使其尾递归):
implicit val iteratorEnumerator = new Enumerator[Iterator] { @annotation.tailrec def apply[E,A] = i match { case _ if iter.isEmpty => i case Done(acc,input) => i case Cont(k) => val x = iter.next apply(iter,k(El(x))) } } 然后: def peekpeek[A] = for (a1 <- peek[A]; a2 <- peek[A]) yield (a1,a2) def peekheadpeek[A] = for (a1 <- peek[A]; a2 <- head[A]; a3 <- peek[A]) yield (a1,a2,a3) def headpeekhead[A] = for (a1 <- head[A]; a2 <- peek[A]; a3 <- head[A]) yield (a1,a3) peekpeek(Iterator(1,3)).run peekheadpeek(Iterator(1,3)).run headpeekhead(Iterator(1,3)).run length(Iterator.from(1).take(1000000)).run 会回来这个: res13: (Option[Int],Some(1)) res14: (Option[Int],Some(2)) res15: (Option[Int],Some(2)) res16: Int = 1000000 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |