Collection.st
changeset 11514 2512add96e15
parent 11498 df4f9e10b141
child 11599 4fd6f122b607
--- a/Collection.st	Tue Feb 03 19:30:11 2009 +0100
+++ b/Collection.st	Wed Feb 04 16:13:22 2009 +0100
@@ -228,6 +228,7 @@
     ^ self withSize:n
 ! !
 
+
 !Collection class methodsFor:'Signal constants'!
 
 emptyCollectionSignal
@@ -383,6 +384,7 @@
     ].
 ! !
 
+
 !Collection methodsFor:'accessing'!
 
 anElement
@@ -1051,6 +1053,31 @@
                           (1 / 7).
                         } sum = (16 / 63) ).
     "
+!
+
+sum:aBlock
+    "for each element in the receiver, evaluate the argument, aBlock
+     and sum up the results. Return the total sum or 0 for an empty collection.
+     Similar to (self collect...) sum, but avoids creation of an intermediate collection."
+
+    |sum|
+
+    self do:[:element |
+        |thisValue|
+
+        thisValue := aBlock value:element.
+        sum isNil ifTrue:[
+            sum := thisValue
+        ] ifFalse:[
+            sum := sum + thisValue
+        ].
+    ].
+    ^ sum ? 0
+
+    "
+     ((1 to:10) collect:[:n | n squared]) sum 
+     ((1 to:10) sum:[:n | n squared])         
+    "
 ! !
 
 !Collection methodsFor:'converting'!
@@ -3328,7 +3355,7 @@
 !Collection class methodsFor:'documentation'!
 
 version
-    ^ '$Header: /cvs/stx/stx/libbasic/Collection.st,v 1.218 2009-01-29 20:21:46 cg Exp $'
+    ^ '$Header: /cvs/stx/stx/libbasic/Collection.st,v 1.219 2009-02-04 15:13:22 cg Exp $'
 ! !
 
 Collection initialize!