Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

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

Comments

@tokland
Copy link

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.

@yhara
Copy link
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 as completed Jun 23, 2012
@tokland
Copy link
Author

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants