On Thu, Nov 8, 2012 at 2:56 PM, Simon King <simon.k...@uni-jena.de> wrote: > On 2012-11-08, Nils Bruin <nbr...@sfu.ca> wrote: >> On Nov 8, 1:17 pm, Simon King <simon.k...@uni-jena.de> wrote: >>> Hi Volker, >>> >>> On 2012-11-08, Volker Braun <vbraun.n...@gmail.com> wrote: >>> >>> > But then you'd always have to write a lot of >>> > boilerplate to return an iterator. Its much easier to use yield, but then >>> > you can't return any additional information about finiteness. >>> >>> No? What's wrong with __len__? >> >> There are iterators where you do know the result is finite but where >> it is hard to predict how many items will be returned, e.g. >> >> ( x for x in range(1000) if expensive_predicate(x) ). >> >> It would be silly to run through this iterable twice: once to get the >> length and establish it's finite and once to actually sum the entries. >> Would you just test for the existence of __len__ ? [On this example it >> actually fails because a generator object doesn't have a __len__ >> attribute. > > My suggestion was that the sum() method (and the prod() method as well) > do things like > def sum(self, L): > try: > n = len(L) > except: > raise ValueError, "the given input is not a finite iterable" > if n not in ZZ: > raise ValueError, "the given input is not a finite iterable" > <do the usual summation and return the result> > > For V = QQ^3, an error would be raised on V.sum(V), simply because len(V) > raises an error. Similarly for V = ZZ. > > For V = GF(5)^3, V.sum(V) would return the sum of all elements, because > len(V) is finite and V is iterable. > > And from the implementation point of view, I guess if P is an iterable > parent (i.e., someone was able to implement __iter__), then usually it > would also be possible to tell the cardinality of P. There are parents > that have a method called cardinality() - why not make __len__ an alias > for the cardinality?
__len__ must return a (machine-sized) int, not elements of ZZ let alone infinity. (That might suffice for this case, but not in general.) Also, this would break if you tried to pass in a (finite) generator, which seems like a perfectly reasonable thing to do. However, I agree with the sentiment that V.sum(W) grossly violates the principle of least surprise as well as being of dubious merit over the builtin sum(...). - Robert -- You received this message because you are subscribed to the Google Groups "sage-devel" group. To post to this group, send email to sage-devel@googlegroups.com. To unsubscribe from this group, send email to sage-devel+unsubscr...@googlegroups.com. Visit this group at http://groups.google.com/group/sage-devel?hl=en.