简体   繁体   中英

Scala Stream Method takeWhile

I'm working through Manning's "Functional Programming in Scala" and have a problem with stream, this is the file:

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:_*))
    }
}

Apply and takeWhile don't compile, I don't know why, logic of it seems allright (apply is taken from the book).

You had a few problems in the code as it was, the amended version:

case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]
sealed trait 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
  }
} // Missed this 


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:_*))
  // there was one too many }  
}

Notice the comments in the code.

First issue was Cons and Empty inside the trait, I don't think that makes sense, it would make sense inside the companion object or on the top-level.

Second issue, if you had indented the code properly you'd easily spot the problems with balancing the brackets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM