我正在完成一些练习:Scala中的函数编程,具体问题5.2。问题是,我从答案密钥拼凑了以下代码。
sealed trait Stream[+A]
{
def take(n: Int): Stream[A] = this match {
case Cons(hs, ts) if n > 1 => cons(h(), t().take(n - 1))
case Cons(hs, _) if n == 1 => cons(h(), empty)
case _ => empty
}
}
case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]
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: _*))
}
我在REPL中得到以下内容:
<console>:10: error: not found: type A
def take(n: Int): Stream[A] = this match {
^
<console>:11: error: not found: value Cons
case Cons(hs, ts) if n > 1 => cons(h(), t().take(n - 1))
^
<console>:11: error: not found: value cons
case Cons(hs, ts) if n > 1 => cons(h(), t().take(n - 1))
^
<console>:12: error: not found: value Cons
case Cons(hs, _) if n == 1 => cons(h(), empty)
^
<console>:12: error: not found: value cons
case Cons(hs, _) if n == 1 => cons(h(), empty)
^
<console>:13: error: not found: value empty
case _ => empty
^
答案 0 :(得分:1)
此代码中有2个问题:
SUM( IF( (AVERAGE('Tenure_Sales Calcs'!I$2:I$1089,'Tenure_Sales Calcs'!J$2:J$1089)>C94)* IF(AVERAGE('Tenure_Sales Calcs'!AF$2:AF$1089)==$B41,1,0),1,0 ) )
和empty
方法位于随播对象cons
要解决此问题,您需要Stream
进入您的班级:
import Stream._
或者您需要明确指定它:
sealed trait Stream[+A] {
import Stream._
def take(n: Int): Stream[A] = this match {
case Cons(hs, ts) if n > 1 => cons(hs(), ts().take(n - 1))
case Cons(hs, _) if n == 1 => cons(hs(), empty)
case _ => empty
}
}
sealed trait Stream[+A] {
def take(n: Int): Stream[A] = this match {
case Cons(hs, ts) if n > 1 => Stream.cons(hs(), ts().take(n - 1))
case Cons(hs, _) if n == 1 => Stream.cons(hs(), Stream.empty)
case _ => Stream.empty
}
}
中的t
和h
的变量名称,而不是case class Cons
和hs
的绑定变量。执行此操作时:
ts
您说要分别将案例类参数提取为case Cons(hs, ts) if n > 1 => Stream.cons(hs(), ts().take(n - 1))
case Cons(hs, _) if n == 1 => Stream.cons(hs(), Stream.empty)
和hs
,并在下一个代码块中使用它们。如果在案例类中调用它们ts
和h
并不重要,则会为它们分配您在匹配中指定的名称。
解决这两个问题并且您的代码应该编译(我亲自使用Scala 2.11.5和Java 1.7进行了测试,但我认为它不重要):
t