I'm using Scala to create a program, but am hitting a wall with how many iterations the loop can do. I'm still quite new when it comes to functional programming and programming in Scala, 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 say a few orders of magnitude bigger than 999999999, say as in the max value of a long. I know i could use a for loop, but i cant see a fold option with that.
Anyone know how this can be achieved?
Thanks.
As you've found, Seqs cannot contain more than Int.MaxValue elements. Until this feature is fixed, don't use a Seq. You can
1) use a while-loop
2) use a for-loop without a sequence
but with these ways you can't use the methods of Scala collections like foldLeft
in your example.
So what you need is an Iterator
. e.g.
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 don't need the full range of BigInt
, use Long
instead as it's significantly faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With