2013-07-01 31 views
0

我试图从Functional Programming in Scala解决练习2。问题如下:执行流的错误

练习2:编写一个函数,用于返回流的前n个元素 。 def采取(N:智力):流[A]

我的解决方案如下:

import Stream._ 
    trait Stream[+A]{ 
      def uncons:Option[(A,Stream[A])] 
      def isEmpty:Boolean = uncons.isEmpty 
      def toList:List[A] = { 
        val listBuffer = new collection.mutable.ListBuffer[A] 
        @annotation.tailrec 
        def go(str:Stream[A]):List[A] = str uncons match { 
          case Some((a,tail)) => listBuffer += a;go(tail) 
          case _ => listBuffer.toList 
        } 
        go(this) 
      } 

      def take(n:Int):Stream[A] = uncons match { 
        case Some((hd,tl)) if (n > 0) => cons(hd,tl.take(n-1)) 
        case _ => Stream() 
      } 
    } 

    object Stream{ 
     def empty[A]:Stream[A] = new Stream[A]{def uncons = None} 
     def cons[A](hd: => A,tl: => Stream[A]):Stream[A] = new Stream[A]{ 
       lazy val uncons = Some((hd,tl)) 
     } 
     def apply[A](as: A*):Stream[A] = { 
       if(as.isEmpty) empty else 
         cons(as.head,apply(as.tail: _ *)) 
     } 
} 

我存储此作为Stream2.scala然后从我执行以下的REPL:

:load Stream2.scala 

当REPL尝试加载我的脚本,它与barfs以下错误:

斯卡拉>:负载STREA m2.scala

Loading Stream2.scala... 
import Stream._ 
<console>:24: error: type mismatch; 
found : Stream[A] 
required: scala.collection.immutable.Stream[?] 
      case Some((hd,tl)) if (n > 0) => cons(hd,tl.take(n-1)) 
                   ^
<console>:25: error: type mismatch; 
found : scala.collection.immutable.Stream[Nothing] 
required: Stream[A] 
      case _ => Stream() 
           ^
<console>:11: error: object creation impossible, since method tailDefined in class Stream of type => Boolean is not defined 
     def empty[A]:Stream[A] = new Stream[A]{def uncons = None} 
            ^
<console>:12: error: object creation impossible, since method tailDefined in class Stream of type => Boolean is not defined 
     def cons[A](hd: => A,tl: => Stream[A]):Stream[A] = new Stream[A]{ 

有人能指出什么可能是错误怎么回事?

+0

尝试在REPL之外执行此操作 - 使用' scalac Stream2.scala'。这可能是因为REPL没有将伴侣对象连接到“Stream”特性。此外似乎还有一些来自标准库Stream的干扰(与Stream的共享名称相同)。在REPL外编译可能会提供更长的错误消息。 – huynhjl

+0

或使用':paste'。 –

+0

或者来到你附近的repl,也许,粘贴文件,https://issues.scala-lang.org/browse/SI-4684 –

回答

1

只需在Stream特征下放置import语句即可。它不适用于您正在导入scala.collection.immutable.Stream的Scala编译器,但不是您的伴侣对象。并且,因为在评论中使用:paste在控制台中感到很伤心,但是将其作为漏洞代码粘贴,否则它不会成为您的特质的伴侣对象

+0

@Alexlv - 粘贴工作。谢谢! –