2017-03-12 104 views
0

我通过曼宁的工作“函数式编程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不进行编译,我不知道为什么,它的逻辑似乎是好的(从书中取材)。

+0

我想你错过了一些'}' – pedrofurla

+0

至少有一个{缺少。 – stholzm

+0

Eclipse不会抱怨括号(“{”,“}”) –

回答

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

请注意,在代码中的注释。

第一个问题是性格内部的缺陷和空缺,我认为这不合理,它会在伴侣对象或顶层内部有意义。

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

+0

感谢您的工作,但它仍然无法编译,突出显示行:case Cons(h,t)if(p(h())) => Stream.cons(h(),t()。takeWhile1(p)),并告诉:名称参数creation()=>。t()。takeWhile1(p)和相同:()=> h() –

+0

你在使用intellij吗?你可能有一个错误的错误。尝试使用SBT编译。 – pedrofurla

+0

哦,你使用的是Eclipse?那更有可能是一个虚假的错误。 – pedrofurla