Sunday, March 17, 2013

list, view and stream - An example to understand the differences

Consider the following simple example :

To understand why we have different values for final lists when using list, views and stream, we have to understand when map evaluation occurs.

The result we got for m1 is of course always List(1, 2, 3) because m1 is entirely evaluated when it is created (c1) so further changes to x variable have no effect.

When you create a view (c2) you didn't evaluate anything, the map operation does nothing, v1 only contains the way how you can get the result when you'll ask for it. It is only when you'll for example materialize a List from a view that the content will be evaluated, that's why each x variable change has a direct effect on the results we got. List(2,3,4) when x=2, and List(3,4,5) when x=3.

Using Stream is a little more different, you must think about Stream as a list that is not yet entirely built. In fact, when it is created (c3), only the first element is evaluated, and once an element has been evaluated, it won't be evaluated again. So in c3 the content is Stream(1, ...) (the "tail" in not yet known) only the first one have been evaluated, and when we apply the toList method (c6) while x=2 we force evaluation of the entire stream, that's why x=3 in c9 has no effect, because the stream have already been entirely evaluated in c6.

No comments:

Post a Comment