Scala View + Stream 组合导致 OutOfMemory 错误.如何用视图替换它? [英] Scala View + Stream combo causing OutOfMemory Error. How do I replace it with a View?

查看:34
本文介绍了Scala View + Stream 组合导致 OutOfMemory 错误.如何用视图替换它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了学习目的,我正在考虑使用惯用的 Scala 解决一个非常简单的问题,Eratosthenes 筛.

I was looking at solving a very simple problem, Eratosthenes sieve, using idiomatic Scala, for learning purposes.

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

I've learned a Stream caches, so it is not so performant when determining the nth element because it's an O(n) complexity access with memoisation of data, therefore not suitable for this situation.

    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 的情况下实现相同功能的正确方法是什么?

The Integer stream is the problematic one. While the prime number filtering is done, JVM runs OutOfMemory. What is the correct way to achieve the same functionality without using Streams?

基本上从整数的角度看素数并显示最后一个元素,没有记忆?

Basically take a view of primes from a view of ints and display the last element, without memoisation?

推荐答案

我遇到过类似的情况,其中流是个好主意,但我不需要存储它的值.为了在不存储流的情况下使用我创建的值(我称之为)ThrowAwayIterator:

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.

这篇关于Scala View + Stream 组合导致 OutOfMemory 错误.如何用视图替换它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆