Big cycle in Scala

I use Scala to create a program, but I click on the wall how many cycles a cycle can execute. I'm still a newbie when it comes to functional programming and Scala programming, but this is what I have at the moment:

val s = Range(1, 999999999).view.foldLeft(0)(_ + _ / whatever); 

But I can’t get the loop to say several orders of magnitude more than 999999999, say, as in the maximum value of long. I know that I can use the for loop, but I cannot see the addition option.

Does anyone know how this can be achieved?

Thanks.

+4
source share
2 answers

As you already found, Seqs cannot contain more Int.MaxValue elements. Until the function is fixed, do not use Seq. You can

1) use while-loop

2) use for loop without sequence

but using these methods you cannot use the Scala collection methods, for example foldLeft in your example.

So you need an Iterator . eg.

 def bigIterator(start: BigInt, end: BigInt, step: BigInt = 1) = Iterator.iterate(start)(_ + step).takeWhile(_ <= end) 

then

 bigIterator(0, BigInt("3000000000")).foldLeft(BigInt(0))(_ + _) 

etc. will work. Note: if you do not need the full range of BigInt , use Long , which is significantly faster.

+6
source
 (BigInt(1) to BigInt(999999999)).view.foldLeft(BigInt(0))(_ + _ / whatever) 

or something like

 BigInt("89893798138989379873") 

if you bring enough time with you.

For instance:

 scala> (BigInt(0) to BigInt("2000000000000000") by BigInt("2000000000")).view.foldLeft(BigInt(0))(_ + _) res: scala.math.BigInt = 1000001000000000000000 
+6
source

Source: https://habr.com/ru/post/1494448/


All Articles