Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you create an Iterable instead of a Sequence in Ceylon?

Tags:

ceylon

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?

like image 476
KPD Avatar asked Mar 01 '15 02:03

KPD


1 Answers

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.

like image 132
gdejohn Avatar answered Oct 13 '22 10:10

gdejohn