0

我试图从Scala 中的函数式编程中解决练习 2 。问题如下:

练习 2:编写一个函数 take 用于返回 Stream 的前 n 个元素。def take(n: Int): Stream[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 尝试加载我的脚本时,它会出现以下错误:

scala> :load Stream2.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]{

有人可以指出这里可能出了什么问题吗?

4

1 回答 1

1

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

于 2013-07-01T07:54:30.640 回答