From: Robert Klemme Date: 2004-08-10T19:16:17+09:00 Subject: Re: empty? and size in Enumerable "Michael Neumann" schrieb im Newsbeitrag news:41189A01.1010504@ntecs.de... > Robert Klemme wrote: > > "Martin DeMello" schrieb im Newsbeitrag > > news:xW%Rc.68814$gE.48438@pd7tw3no... > > > >>Robert Klemme wrote: > >> > >>>Hm, sounds to me like it was not general enough to include it in > >>>Enumerable. Before I see that method I'd prefer to have size and > > > > empty? > > > >>>in Enumerable. Just my 0.02 EUR... > >> > >>Can empty? be reliably implemented in terms of each for every > >>enumerable? I can't think of an obvious problem with it, but that > >>doesn't mean there isn't one. > > > > > > Yes, that's possible IMHO. My suggestion would be: > > > > module Enumerable > > # O(1) > > def empty? > > each { return false } > > true > > end > > > > # O(n) > > def size > > inject(0) {|s,| s+1} > > end > > end > > > > Do you see any problems? There's only the little disadvantage that size > > is O(n) while there are most likely more efficient implementations for > > certain collections. But classes like Array and Hash provide their own > > implementation anyway, which then overrides Enumerable#size. So there's > > no drawback IMHO, only the advantage that you don't have to write it if > > you have a collection that can determine its size only via a complete > > iteration. > > Hehe, and how long does it take to determine the size of infinite or > cyclic Enumerable's? ;-) A tad longer, I'd say. :-) There's clearly no point in doing that. But that's the best argument against Enumerable#size that I've heard so far. Probably there should be a distinction like BoundEnumerable as sub module of Enumerable. Thank's for that hint! Regards robert