scala前向引用扩展了定义
发布时间:2020-12-16 18:55:08 所属栏目:安全 来源:网络整理
导读:case object Empty extends Stream[Nothing]case class Cons[+A](h: () = A,t: () = Stream[A]) extends Stream[A]sealed trait Stream[+A] { def toList: List[A] = { val buf = new collection.mutable.ListBuffer[A] def go(s: Stream[A]): List[A] = s m
case object Empty extends Stream[Nothing] case class Cons[+A](h: () => A,t: () => Stream[A]) extends Stream[A] sealed trait Stream[+A] { def toList: List[A] = { val buf = new collection.mutable.ListBuffer[A] def go(s: Stream[A]): List[A] = s match { case Cons(h,t) => buf += h() go(t()) case _ => buf.toList } go(this) } def cons[A](hd: => A,tl: => Stream[A]): Stream[A] = Stream.cons(hd,tl) def empty = Stream.empty def unfold[A,S](z: S)(f: S => Option[(A,S)]): Stream[A] = f(z) match { case Some((h,t)) => cons(h,unfold(t)(f)) case None => empty } def take(n: Int): Stream[A] = unfold((this,n)) { case (Cons(h,t),1) => Some((h(),(empty,0))) case (Cons(h,n) if n > 1 => Some((h(),(t(),n-1))) case (Empty,0) => None } } object Stream { def cons[A](hd: => A,tl: => Stream[A]): Stream[A] = Cons(() => hd,() => tl) def empty[A]: Stream[A] = Empty val ones: Stream[Int] = Stream.cons(1,ones) } object StreamTest { def main(args: Array[String]) { //why compile error: forward reference extends over definition of value ones /*val ones: Stream[Int] = Stream.cons(1,ones) println(ones.take(5).toList)*/ println(Stream.ones.take(5).toList) } } 为什么编译错误?:前向引用扩展了有价值的定义 在对象’Stream’中, 但在主要方法中,它不行(但是……同样的合成!) 解决方法
本地vals不是成员.
对于测试代码,请执行以下操作: object StreamTest extends App { //def main(args: Array[String]) { //why compile error: forward reference extends over definition of value ones val ones: Stream[Int] = Stream.cons(1,ones) println(ones.take(5).toList) println(Stream.ones.take(5).toList) //} } 块中的限制措辞为in the spec here,其他建议是使其成为块中的惰性val,具有相同的效果. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |