5

I've read the walkthrough about sequences but I don't really understand why there is a way to define both a literal Iterable and a literal Sequence.

{String+} iterable = {"String1", "String2"};
[String+] sequence = ["String1", "String2"];

Since Sequence is a subtype of Iterable, it seems like it should be able to do everything the Iterable does and more.

What's the need for having the Iterable curly braces initializer then? When would you want to use it instead of the square bracket Sequence version?

KPD
  • 5,281
  • 4
  • 20
  • 19

2 Answers2

7

Streams are lazy.

import ceylon.math.float {random}

value rng = {random()}.cycled;

So that's a lazy, infinite stream of random numbers. The function random isn't invoked when you construct the stream. On the other hand, a sequence would eagerly evaluate its arguments, in this case giving you the result of a single invocation of random over and over. Another example:

function prepend<Element>(Element first, {Element*} rest) => {first, *rest};

Here, the stream rest is spread over the resulting stream, but only on demand.

gdejohn
  • 7,451
  • 1
  • 33
  • 49
5

Exactly what @gdejohn said, but I want to point out that laziness is especially important for performance if you're going to apply multiple operations to the stream, for example:

value stream = { random() }.cycled
        .filter((x) => x>0.5)
        .map((x) => (x*100).integer);
printAll(stream.take(1000));

Here we avoid ever materializing a whole sequence of length 1000, since every one of the intermediate operations: cycled, filter(), map(), and take() returns a stream. And even printAll() doesn't need to materialize a sequence.

Gavin King
  • 3,182
  • 1
  • 13
  • 11
  • Apart from the `random()` stuff being called several times (which I didn't realize until now), the same would have worked with `[...]`, wouldn't it? `[ 5 ].cycled` will still return a lazy iterable. – Paŭlo Ebermann Oct 29 '15 at 23:37
  • Yes, `[ 5 ].cycled` is lazy. It doesn't try to materialize an infinite sequence :-) – Gavin King Oct 29 '15 at 23:38