// Streams // // Chapter 12, Scala Programming by Example // def sumPrimes(start: Int, end: Int): Int = { var i = start var acc = 0 while (i < end) { if (isPrime(i)) acc += i i += 1 } acc } // or def sumPrimes(start: Int, end: Int) = sum(range(start, end) filter isPrime) // more concise, but also less efficient ... // generate lists "on demand" -> streams // has first, tail, isEmpty, range methods def print[A](xs: Stream[A]) { if (!xs.isEmpty) { Console.println(xs.head); print(xs.tail) } } (Stream.range(1000, 10000) filter isPrime).tail.head // Streams do not support :: or ::: , use Stream.cons(x,xs) and xs append ys instead // see also chapter 13: Iterators ... // Stream-based Sieve of Eratosthenes // from http://en.literateprograms.org/Sieve_of_Eratosthenes_(Scala) def ints(n: Int): Stream[Int] = Stream.cons(n, ints(n+1)) def primes(nums: Stream[Int]): Stream[Int] = Stream.cons(nums.head, primes ((nums tail) filter (x => x % nums.head != 0)) )