tags:

views:

282

answers:

2

It seems that both of these are lazy and allow you to keep returning elements to your heart's content. What's the difference between the two?

+5  A: 

This thread in the Scala mailing list goes into some detail to answer your question. To excerpt the most relevant part, Tony Morris says:

One is pure, the other is imperative (Iterator). You might notice that Iterator.next is side-effecting. Imagine changing its next method to return a tuple containing an Iterator instead. i.e. instead of returning a T (for Iterator[T]), it returns a (T, Iterator[T]).

What do we have now? A stream! next._1 is head and next._2 is tail.

A better question might be "why bother having Iterators (or imperative constructs)?". I suspect the answer has something to do with Java and targetting the JVM i.e. a flawed premise.

Jonathan Feinberg
Why is targeting the JVM a flawed premise? The JVM is key to Scala's survival and growth.
Seun Osewa
It is a flawed premise, because it introduces a imperative construct into what was meant to be a functional language.
jdmichal
Tony Morris is well known on Scala mailing lists for being a functional purist, and tends to come off as a bit of a troll when he starts talking that way. Since Scala is a multi-paradigm programming langauge, it's intended to do imperative programming well in addition to functional programming. (You'll notice that there's a lot of syntactic decisions in Scala that make Ruby programmers feel right at home.) Thus things that Tony thinks are flawed in the context of functional programming may make sense in Scala, and his rants can often be safely ignored.
Ken Bloom
+9  A: 

Stream memoises and Iterator does not. You can traverse the same Stream multiple times and get the same result each time. Iterator, on the other hand, can only be traversed once.

Walter Chang
With regards to the memoization - if I access the Nth element, is the access time O(1) or O(N)?
ryeguy
@ryeguy It's O(n) because Stream builds a linked list to cache element values.
Walter Chang