[squeak-dev] Re: Collection>>sum implementation
Ramon Leon
ramon.leon at allresnet.com
Tue Aug 12 17:25:15 UTC 2008
> nil is actually a fine "mysticalObject" and it arises
> naturally in the
> implementation of #sum that I would favor:
>
> Collection>>sum
> "Answers the sum of the elements in the receiver, nil if empty"
> | sum |
> self do:[:value|
> sum := sum ifNil:[value] ifNotNil:[sum + value].
> ].
> ^sum
>
> > But if you want #sum rather than #sumFromZero: then for the
> numerical
> > case it sufficies to do
> >
> > mySalarySum := myBigSalaryVector sum + 0
>
> With the above this becomes:
>
> mySalarySum := myBigSalaryVector sum ifNil:[0 euro].
>
> (assumes unit package with Euro support loaded).
>
> Cheers,
> - Andreas
+1 on this, most idiomatic looking solution so far since using ifNil: is a
common idiom for defaulting a value. It also properly handles collections
which might contain nil's by skipping over the nil while summing without
assuming any ordering by trying to use #first.
Ramon Leon
More information about the Squeak-dev
mailing list
|