我是 Scala 语言的新手.
I'm new to the Scala language.
我需要 Long 类型的 Range.
I need Range for Long type.
我需要一个包含第 1 步的 [1, 2, 3 ... 10000000] 列表.如果我使用 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' 是强制性的,以告知编译器文字是长整数而不是整数.
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)...