Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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

or something like

BigInt("89893798138989379873")

if you bring enough time with you.

For example:

scala> (BigInt(0) to BigInt("2000000000000000") by BigInt("2000000000")).view.foldLeft(BigInt(0))(_ + _)
res: scala.math.BigInt = 1000001000000000000000
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top