斯卡拉范围长 [英] scala Range for Long

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

问题描述

我是Scala语言的新手.

I'm new to the Scala language.

我需要Long类型的范围.

I need Range for Long type.

在步骤1中,我需要一个[1、2、3 ... 10000000]的列表.如果使用直到/到,则由于使用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.

我尝试编写一个简单的函数,该函数期望一个开始,一个结束和一个空的List,并生成一个[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 :: list

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]或如何优化功能.如何避免内存不足?

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)...

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

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