Array#lazy_slice: create a lazy Enumerable from an array range slice. #1

Closed
tokland opened this Issue Jun 2, 2012 · 2 comments

Comments

Projects
None yet
2 participants

tokland commented Jun 2, 2012

Does an extensions like this make sense to be included?

require 'enumerable/lazy'

class Array
  def lazy_slice(range)
    Enumerator.new do |yielder|
      range.each do |index|
        yielder << self[index]
      end
    end.lazy
  end
end

big_array = (0..10000).to_a # fake array, it won't generally be a range
p big_array.lazy_slice(9995..10000).map { |x| 2*x }.to_a
#=> [19990, 19992, 19994, 19996, 19998, 20000]

In this example I am trying to highlight that the currently available big_array.lazy.drop(9995).take(6) wouldn't be efficient.

Owner

yhara commented Jun 23, 2012

It does make sense when the range is large enough. When the range is small, you can write just some_big_array.slice(range).

But we can't add lazy_slice to Enumerable::Lazy because an Enumerable class does not always have
the indexing method '[]' (For example, the IO class includes Enumerable but does not have IO#[].)

By the way, Enumerable#lazy is accepted as Ruby 2.0 feature. I've updated the readme.

@yhara yhara closed this Jun 23, 2012

tokland commented Jun 26, 2012

It does make sense when the range is large enough. When the range is small, you can write just some_big_array.slice(range).

Yes, well, no laziness then :-)

But we can't add lazy_slice to Enumerable::Lazy because an Enumerable class does not always have
the indexing method '[]'

Of course, slices on real lazy objects must do a drop+take. Just that's Array#lazy_slice.

By the way, Enumerable#lazy is accepted as Ruby 2.0 feature. I've updated the readme.

I know, I am very excited about it :-)

FYI, I added this method in my fork: https://github.com/tokland/enumerable-lazy

Regards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment