0

我正在考虑使用惯用的 Scala 解决一个非常简单的问题,即 Eratosthenes 筛子,用于学习目的。

我已经学习了一个 Stream 缓存,因此在确定第 n 个元素时它的性能不是很好,因为它是一个 O(n) 复杂性访问,带有数据的记忆,因此不适合这种情况。

    def primes(nums: Stream[Int]): Stream[Int] = {
        Stream.cons(nums.head,
            primes((nums tail) filter (x => x % nums.head != 0)))
    }

    def ints(n: Int): Stream[Int] = {
        Stream.cons(n, ints(n + 1))

    };
    def nthPrime(n: Int): Int = {
        val prim = primes(ints(2)).view take n toList;
        return prim(n - 1);
    };

整数流是有问题的流。完成素数过滤后,JVM 运行 OutOfMemory。在不使用 Streams 的情况下实现相同功能的正确方法是什么?

基本上从整数的角度来看素数并显示最后一个元素,而不需要记忆?

4

1 回答 1

1

I have had similar cases where a stream was a good idea, but I did not need to store it's values. In order to consume the stream without storing it's values I created (what I called) ThrowAwayIterator:

class ThrowAwayIterator[T](var stream: Stream[T]) extends Iterator[T] {
  def hasNext: Boolean = stream.nonEmpty
  def next(): T = {
    val next = stream.head
    stream = stream.tail
    next
  }
}

Make sure that you do not store a reference to the instance of stream that is passed in.

于 2013-04-25T19:03:14.323 回答