From: "trans. (T. Onoma)" Date: 2004-10-08T02:18:22+09:00 Subject: Re: Range behavior (Re: [RCR] New [] Semantics) On Thursday 07 October 2004 12:51 pm, Brian Candler wrote: | On Fri, Oct 08, 2004 at 01:19:21AM +0900, trans. (T. Onoma) wrote: | > - The Ranges #succ can be overridden as either a proc or a an object. | > If an object, then each step is simply determined by the addition | > of that object, i.e. self + #succ. If that succ object is a | > Numeric, then the range is a numeric range and can gain the | > speed advantages of the faster modulo #member? code. | | I think more generally, if you provide a proc, then you don't need to | stipulate addition here; the proc could be { |x| x+1 }, or it could be | { |x| x*2 } Except you gain no speed advantages in dealing with numeric ranges, which I'm sure is the most common type of range in use. | class DiscreteRange4 | include Enumerable | def initialize(seed, count, succmeth=:succ) | @seed = seed | @count = count | @succmeth = succmeth | end | def each | val = @seed | if @succmeth.respond_to?(:call) | @count.times do | yield val | val = @succmeth.call(val) | end | else | @count.times docreating | yield val | val = val.send(@succmeth) | end | end | end | end | | DiscreteRange4.new(10,5).each { |x| puts x } | DiscreteRange4.new(10,5,proc {|x| x=x-1}).each { |x| puts x } | | (leaving aside that we might want to replace count with an end value or an | end test proc) | | So, we've made an iterator generator. I'm not sure how useful this is, | because in these cases it's probably simpler just to write your own | iterator: | | x = 10 | 5.times do | puts x | x = x-1 | end | | Especially where the range is given by a length, and so you can use n.times | { block } to run it. The why do we have a range at all? I can easily test x >= a && x <= b, too. So interval functionality seems trivial. On the other hand, a Range has the advantages of being a portable and pollable iterator, base on inherent traits of the seed value (i.e. succ) --but being able to override this is hardly useless either. It's advantage is that it is a self contained object with useful methods. Do you think DiscreteRange (Range) and ContinuousRange (Interval) need to be separated in some way as has been suggested? T.