Scala Stream [Int] #foldLeft and Stream [Int] #sum give different results

This question is related to the sum of primes of the euler project and Stream.view , but there is a bit of a twist. I want to calculate the sum of all primes below two million. I am creating a prime generator defined as:

lazy val primes: Stream[Int] = 2 #:: Stream.from(3).filter(i => primes.takeWhile(j => j * j <= i).forall(i % _ > 0)) 

I wrote two tests, one used Stream [Int] #foldLeft and one used Stream [Int] #sum:

  @Test def testEuler010a { primes.view.takeWhile(_ < 2000000).foldLeft(0L)(_ + _) mustEqual 142913828922L } @Test def testEuler010b { primes.view.takeWhile(_ < 2000000).sum mustEqual 142913828922L } 

testEuler010a gives the correct answer, and testEuler010b does not respond with the answer 1179908154 . I would expect that Stream[Int]#foldLeft(0L)(_ + _) would be identical to Stream[Int].sum , but it is not. Even if I materialize Stream with toList() , I get the same mismatch. Is this a false assumption that these methods should give the same result?

I am using Scala 2.9.1.final.

+4
source share
1 answer

The problem seems to be crowded. They give me the same results:

 (primes map (_.longValue) takeWhile (_ < 2000000)).sum (primes map (_.longValue) takeWhile (_ < 2000000)).foldLeft(0L)(_ + _) 

I believe that the difference between sum and foldLeft is that the type of the result sum matches the type of the elements to be summed (as required by the Numeric attribute ), but foldLeft may have a different type of result that you achieve by writing 0L .

+11
source

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


All Articles