4 ms·
The method should be: array<number>.sum The article is correct .sum shouldn't be on an array, but sum shouldn't be global either. This is why generics exist.
by evanmoran 18y ago
The method should be: array<number>.sum
The article is correct .sum shouldn't be on an array, but sum shouldn't be global either. This is why generics exist.
- omouse 18y agoOr you can have a sum method that accepts a block/lambda/anonymous function as an argument. This is done in Smalltalk with detectSum. people detectSum: [ :person | person age ]. items detectSum: [ :item | item price ].
- jdminhbg 18y agoIn Ruby, this would be: class Array def detectSum(&block) self.map(&block).sum end end >> [1, 2, 3].detectSum {|i| i**2} => 14 Most Ruby people though would just call #map and #sum in succession on an ad hoc basis.
- omouse 18y agoEw, how inefficient. Here is the Smalltalk code: detectSum: aBlock "Evaluate aBlock with each of the receiver's elements as the argument. Return the sum of the answers." | sum | sum := 0. self do: [:each | sum := (aBlock value: each) + sum]. ^ sum Anyway, my point still stands. Better to accept a block than to use a sum method that assumes the Array consists of numbers
- evanmoran 18y agoI agree that using blocks/closures is a powerful and useful mechanism -- In fact I think that they are a great implementation technique for this method. What this comes down to for me is: what makes the best interface? Specifically: myArray.sum() is much easier to read and use. In a world where we have to maintain our code much longer then we write it this simplicity is very valuable. Secondly, it is important to note that since the array uses generics it is not necessary to check that the items are numbers, as any attempt to insert a non-number would have thrown an error. So in summery I agree with you completely that array<variant>.sum should _not_ exist. But I hope you see my point that array<number>.sum _should_ exist. (If the code enforces the numbers to exist in the array there is no reason not to include the sum method!)