我通过曼宁的工作“函数式编程Scala中”并与流的问题,这是文件:斯卡拉流方法TakeWhile
package chapter05
sealed trait Stream[+A]{
case object Empty extends Stream[Nothing]
case class Cons[+A](h:() => A, t:() => Stream[A]) extends Stream[A]
def headOption: A = this match {
case Empty => throw new Exception("optional")
case Cons(h, t) => h()
}
def toList: List[A] = this match {
case Cons(h, t) => h() :: t().toList
case Empty => Nil
}
def takeWhile1(p: A => Boolean): Stream[A] =
this match {
case Cons(h, t) if (p(h())) => Stream.cons(h(), t().takeWhile1(p))
case _ => Empty
}
object Stream {
def cons[A](hd: => A, tl : => Stream[A]): Stream[A] = {
lazy val head = hd
lazy val tail = tl
Cons(() => head,() => tail)
}
def empty[A]: Stream[A] = Empty
def apply[A](as: A*): Stream[A] =
if (as.isEmpty) empty else cons(as.head, apply(as.tail:_*))
}
}
应用和takeWhile不进行编译,我不知道为什么,它的逻辑似乎是好的(从书中取材)。
我想你错过了一些'}' – pedrofurla
至少有一个{缺少。 – stholzm
Eclipse不会抱怨括号(“{”,“}”) –