长期的Scala范围 [英] scala Range for Long

查看:33
本文介绍了长期的Scala范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Scala 语言的新手.

I'm new to the Scala language.

我需要 Long 类型的 Range.

I need Range for Long type.

我需要一个包含 [1, 2, 3 ... 10000000] 的列表和第 1 步.如果我使用 until/to,我会因为使用 Long 而不是 Int 得到一个错误.

I need a List of [1, 2, 3 ... 10000000] with step 1. If I use until/to I get an error because of using Long instead of Int.

我尝试编写一个简单的函数,它需要一个开始、一个结束和一个空列表,并生成一个 [start .. end] 的列表.

I try to write simple function which expects a start, an end and and an empty List and generates a List of [start .. end].

这是我的功能:

def range_l(start : Long, end : Long, list : List[Long]) : List[Long] = {
    if (start == end){
        val add_to_list = start :: list
        return add_to_list
    }
    else {
        val add_to_list = start :: list
        range_l(start + 1, end, add_to_list)
    }
}

如果我这样称呼它:range_l(1L, 1000000L, List()) 我在以下行中得到 OutOfMemory 错误:add_to_list = start ::列表

If I call it like: range_l(1L, 1000000L, List()) i get OutOfMemory error in the following line: add_to_list = start :: list

你能给我什么建议?如何获得 Range[Long] 或如何优化函数.如何避免 OutOfMemory?

What can you advice me? How can I get Range[Long] or how can I optimize the function. How can I avoid OutOfMemory?

谢谢.

推荐答案

您可以使用以下语法创建这样的范围:

You can create such a range by using the following syntax:

val range = 1L to 10000000L

'L' 是强制性的,用于通知编译器文字是 long 而不是 int.

The 'L' is mandatory to inform the compiler that the litterals are longs and not ints.

然后您可以在实例range 上使用几乎所有List 方法.它不应该填满你的记忆,因为中间值是在需要时生成的.范围可以传递给任何需要 Traversable[Long]Seq[Long]Iterable[Long] 等的方法.

You can then use almost all List methods on the instance range. It should not fill you memory because the intermediate values are generated when needed. The range can be passed to any method expecting a Traversable[Long], a Seq[Long], an Iterable[Long], etc.

然而,如果你真的需要一个 List 只需调用 range.toList(并增加堆大小以容纳所有列表元素)...

However, if you really need a List just call range.toList (and increase the heap size to accommodate all the list elements)...

这篇关于长期的Scala范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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