Scala Stream方法takeWhile

时间:2017-03-12 18:44:33

标签: algorithm scala functional-programming

我正在通过Manning" Scala中的功能编程"并且有一个流问题,这是文件:

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

申请并采取不编译,我不知道为什么,它的逻辑似乎是正确的(适用于本书)。

1 个答案:

答案 0 :(得分:1)

您在代码中遇到了一些问题,修改后的版本:

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 }  
}

注意代码中的注释。

第一个问题是Cons和Empty内在特质,我不认为这是有道理的,它会在伴侣对象内或顶层有意义。

第二个问题,如果你正确地缩进代码,你很容易发现平衡括号的问题。