Scala Range for Long

I am new to Scala.

I need a range for a long type.

I need a list from [1, 2, 3 ... 10000000] with step 1. If I use before / to get an error due to using Long instead of Int.

I am trying to write a simple function that expects a start, end and an empty list and generates a list from [start .. end].

Here is my function:

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

If I name it as:, range_l(1L, 1000000L, List())I get an error OutOfMemoryin the following line:add_to_list = start :: list

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

Thank.

+3
source share
3 answers

, :

val range = 1L to 10000000L

"L" , , - longs, ints.

List range. , . , Traversable[Long], a Seq[Long], a Iterable[Long] ..

, List range.toList ( )...

+7

, , . Stream .

def stream(i: Long = 1): Stream[Long] = i #:: stream(i + 1)

creates an endless stream where the difference between the elements is 1. Since Stream is a lazy collection, you will not get any errors. To iterate over 10,000,000 items, you simply use the following:

val range = stream take 10000000
for (i <- range) {
  ...
}

take 10000000will return a value Streamwith a size of 10000000. Since Streamthis is Iterable, you can pass it in addition to comprehansion.

+5
source

All Articles