From: Jim Weirich Date: 2004-04-07T17:11:21+09:00 Subject: Re: deciding between ruby and python gabriele renzi wrote: > guess why you can't use a prime? because you can't pause the yielding. > You're forced to use the whole number of Prime number that are > actually.. infinite. > So, you discover that you can't zip it cause zip calls to_ary. Alas, that is a limitation of the internal iterator paradigm that Ruby uses. Infinite lists and things like the "same fringe" problem (see http://onestepback.org/articles/same_fringe/index.html) are all examples of problems that need more power than internal iterators provide. Fortunately, the these types of problems are less common that those addressed by internal iterators. Add when we need bigger guns in Ruby, they are available. The generator package is now standard in Ruby, so lazy zips are fairly easy to write when you need them. I find it fascinating how the different choices in iteration methods effect how language users perceive and use the language. Python starts with external iterators and uses continuation-like generators to gain back the convenience of writing internal iterators. Ruby starts with internal iterators and uses continuations to gain back the flexibility of external iterators. Different trade offs with different implications for users. But in the end, approximately equivalent. > lazy generators allows you to use just one element at a time, so zip > can be used for any kind of enumerable. I did check out the generator package before I wrote this, so I might as well share some code. Here's one way to write a lazy zip in Ruby. require 'generator' require 'mathn' def lazy_zip(*args) gens = args.collect { |en| Generator.new(en) } Generator.new do |composite| while gens.all? { |g| g.next? } composite.yield gens.collect { |g| g.next } end end end primes = Prime.new pzip = lazy_zip(primes, 1..4) 4.times { p pzip.next } Will print ... [2, 1] [3, 2] [5, 3] [7, 4] -- -- Jim Weirich jim@weirichhouse.org http://onestepback.org ----------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)