Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite streams in Scala

Tags:

stream

scala

Say I have a function, for example the old favourite

def factorial(n:Int) = (BigInt(1) /: (1 to n)) (_*_) 

Now I want to find the biggest value of n for which factorial(n) fits in a Long. I could do

(1 to 100) takeWhile (factorial(_) <= Long.MaxValue) last 

This works, but the 100 is an arbitrary large number; what I really want on the left hand side is an infinite stream that keeps generating higher numbers until the takeWhile condition is met.

I've come up with

val s = Stream.continually(1).zipWithIndex.map(p => p._1 + p._2) 

but is there a better way?

(I'm also aware I could get a solution recursively but that's not what I'm looking for.)

like image 664
Luigi Plinge Avatar asked Jun 20 '11 07:06

Luigi Plinge


People also ask

Does Scala have Streams?

Scala has several data structures to support lazy operations: Stream, Iterator, and View.

What is a stream in Scala?

The Stream is a lazy lists where elements are evaluated only when they are needed. This is a scala feature. Scala supports lazy computation. It increases performance of our program. Streams have the same performance characteristics as lists.


1 Answers

Stream.from(1) 

creates a stream starting from 1 and incrementing by 1. It's all in the API docs.

like image 170
Kim Stebel Avatar answered Sep 23 '22 20:09

Kim Stebel