2015-12-22 10:37 GMT+01:00 Sven Van Caekenberghe <sven@stfx.eu>:

> On 22 Dec 2015, at 10:22, Nicolas Cellier <nicolas.cellier.aka.nice@gmail.com> wrote:
>
>
>
> 2015-12-22 3:46 GMT+01:00 Ben Coman <btc@openinworld.com>:
> On Wed, Dec 2, 2015 at 3:38 AM, Tudor Girba <tudor@tudorgirba.com> wrote:
> > I am saying that if you want sum: to be generic, it cannot assume a *specific* Zero object.
> > And sum:�� should be generic because of its name.
>
> This seems the crux of the disparate viewpoints, which is why I
> suggested return a *generic* Zero object as follows...
>
> > On 04 Dec 2015, at 01:49, Ben Coman <btc@openInWorld.com> wrote:
> > do something like...
> >
> >�� �� Collection>>sum
> >�� �� �� ��| sum sample |
> >�� �� �� ��self isEmpty ifTrue: [ ^ ArithmeticZero ].
> >�� �� �� ��sample := self anyOne.
> >�� �� �� ��sum := self inject: sample into: [ :accum :each | accum + each ].
> >�� �� �� �� ^ sum - sample
>
>
> Nice, but generic zero can't work: you sometimes need to decide if it is the zero of vector space, or of associated field.
> The generic zero can't behave as both say a matrix and a scalar...

Indeed, that is what I said the first time Ben proposed this.

But I am curious, Nicolas, what you think of this, with your math background/interest ?


This is what I had in old app (in the 90s):

SequenceableCollection>>sum: aBlock
������ "answer the sum of all elements after applying a Block"
������ | sum |
������ self isEmpty ifTrue: [^0].
������ sum := aBlock value: (self at: 1).
������ 2 to: self size do: [:i | sum := sum + (aBlock value: (self at: i))].
������ ^sum

Collection>>sum: aBlock
������ "answer the sum of all elements after applying a Block"
������ | sum |
������ sum := 0.
������ self do: [:e | sum := sum + (aBlock value: e)].
������ ^sum

I find sum: much more expressive than inject:into:

If we really find that it adds semantic value to inject:into: we may also implement optionnal:

Collection>>sum: aBlock to: initialValue
������ "answer the sum of all elements after applying a Block"
������ | sum |
������ sum := initialValue.
������ self do: [:e | sum := sum + (aBlock value: e)].
������ ^sum
Collection>>sum: aBlock
������ ^self sum: aBlock to: 0

This way, no (#anyOne,#-) trick required, that's why I prefer sum:to: to sum:ifEmpty:...
For example, I had symbolic algebra, and the #- trick would have required further simplification of the sum.

So I don't have any mathematical solution, just pragmatic ones:
- I agree on this: no need for many selectors, one or maximum two should be enough
- I wouldn't care too much and would just answer 0 for empty collection because we have inject:into: or optionnally sum:to: for exotic cases