SICP says that iterative processes (e.g. Newton method of square root calculation, "pi" calculation, etc.) can be formulated in terms of Streams
.
Does anybody use streams
in Scala to model iterations?
SICP says that iterative processes (e.g. Newton method of square root calculation, "pi" calculation, etc.) can be formulated in terms of Streams
.
Does anybody use streams
in Scala to model iterations?
Here is one way to produce the stream of approximations of pi:
Now, say you want the 200th iteration:
...or the 300000th:
Streams are extremely useful when you are doing a sequence of recursive calculations and a single result depends on previous results, such as calculating pi. Here's a simpler example, consider the classic recursive algorithm for calculating fibbonacci numbers (1, 2, 3, 5, 8, 13, ...):
One of the main points of this code is that while very simple, is extremely inefficient.
fib(100)
almost crashed my computer! Each recursion branches into two calls and you are essentially calculating the same values many times.Streams allow you to do dynamic programming in a recursive fashion, where once a value is calculated, it is reused every time it is needed again. To implement the above using streams:
Whereas the recursive solution runs in O(2^n) time, the Streams solution runs in O(n^2) time. Since you only need the last 2 generated members, you can easily optimize this using
Stream.drop
so that the stream size doesn't overflow memory.