From: Shugo Maeda Date: 2011-10-31T11:48:15+09:00 Subject: [ruby-core:40544] [ruby-trunk - Feature #4890] Enumerable#lazy Issue #4890 has been updated by Shugo Maeda. Assignee set to Yukihiro Matsumoto Target version changed from 1.9.x to 2.0 Hi, Yutaka HARA wrote: > require 'prime' > INFINITY = 1.0 / 0 > p (1..INFINITY).lazy.map{|n| n**2+1}.select{|m| m.prime?}.take(100) I prefer Enumerable#lazy to Enumerable#lazy_map or rude_map because Enumerable#lazy can be used polymorphically as Enumerable. I hope that Enumerable#lazy will be included in Ruby 2.0. Is there any reason why it shouldn't be included in Ruby 2.0? FYI, Scala has a similar method called view. I don't know whether the name view is better than lazy because I'm not a native English speaker. scala> val v = Vector(1 to 10: _*) v: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> v.view.map(_ + 1).map(_ * 2) res0: scala.collection.SeqView[Int,Seq[_]] = SeqViewMM(...) scala> v.view.map(_ + 1).map(_ * 2).force res1: Seq[Int] = Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22) In Ruby, results are always arrays, so we can use to_a instead of force. But the name force looks better than to_a for me. Scala also has a method called withFilter, which is something like lazy_select. scala> v.withFilter(_ % 2 == 0).map(_ * 1) res12: scala.collection.immutable.Vector[Int] = Vector(2, 4, 6, 8, 10) I guess it is introduced for the for expression, which is equivalent to list comprehension in Haskell. ---------------------------------------- Feature #4890: Enumerable#lazy http://redmine.ruby-lang.org/issues/4890 Author: Yutaka HARA Status: Open Priority: Normal Assignee: Yukihiro Matsumoto Category: core Target version: 2.0 =begin = Example Print first 100 primes which are in form of n^2+1 require 'prime' INFINITY = 1.0 / 0 p (1..INFINITY).lazy.map{|n| n**2+1}.select{|m| m.prime?}.take(100) (Example taken from enumerable_lz; thanks @antimon2) = Description Enumerable#lazy returns an instance of Enumerable::Lazy. This is the only method added to the existing bulit-in classes. Lazy is a subclass of Enumerator, which includes Enumerable. So you can call any methods of Enumerable on Lazy, except methods like map, select, etc. are redefined as 'lazy' versions. = Sample implementation (()) (also attached to this ticket) =end -- http://redmine.ruby-lang.org