From: David Masover on
On Sunday, August 01, 2010 05:45:02 pm Andrew Wagner wrote:
> How can I get a lazy array in Ruby? E.g., in Haskell, I can talk about
> [1..], which is an infinite list, lazily generated as needed. I can also do
> things like "iterate (+2) 0", which applies whatever function I give it to
> generate a lazy list. In this case, it would give me all even numbers.
> Anyway, I'm sure I can do such things in Ruby, but can't seem to work out
> how.

In your specific case, you could do this:

list = (1..(1.0/0))

But you can't necessarily iterate it like you want, so no, Ruby does not have
an equivalent feature. You can do things like this:

list.first(10).map{|x| x*2}

That would give you the first ten even numbers, but it wouldn't work the way
you expect -- first(10) actually dumps those into an array, and map
immediately creates a new array from that one. It's not at all like the
Haskell/functional concept.

So, you can do similar and interesting things, and you can probably get close
to the semantics (roughly), but the implementation is going to be very
imperative/eager, and not at all lazy. You can do lazy-ish transformations by
writing your own Enumerators, but those aren't as elegant to write.

I think this is a solvable problem, even solvable within Ruby, I just haven't
really seen it done, and there doesn't seem to be anything in the core
language that really does it.