Add Iterator.fold aggregative function
authorMaciej Piechotka <uzytkownik2@gmail.com>
Sun, 17 Oct 2010 16:14:59 +0000 (17:14 +0100)
committerMaciej Piechotka <uzytkownik2@gmail.com>
Sun, 17 Oct 2010 16:18:11 +0000 (17:18 +0100)
gee/iterator.vala
tests/testcollection.vala

index 3b09d63..48c749e 100644 (file)
  *     Didier 'Ptitjes Villevalois <ptitjes@free.fr>
  */
 
+namespace Gee {
+       public delegate A FoldFunc<A, G> (G g, owned A a);
+}
+
 /**
  * An iterator over a collection.
  *
@@ -68,5 +72,23 @@ public interface Gee.Iterator<G> : Object {
         * beginning and after {@link remove} call and true otherwise.
         */
        public abstract bool at_element { get; }
+       
+       /**
+        * Standard aggragation function.
+        *
+        * It takes a function, seed and first element, returns the new seed and
+        * progress to next element when the operation repeats.
+        *
+        * Operation moves the iterator to last element in iteration. If iterator
+        * points at some element it will be included in iteration
+        */
+       public virtual A fold<A> (FoldFunc<A, G> f, owned A seed)
+       {
+               if (at_element)
+                       seed = f (get (), (owned) seed);
+               while (next ())
+                       seed = f (get (), (owned) seed);
+               return (owned) seed;
+       }
 }
 
index 06d5d94..0f2be80 100644 (file)
@@ -43,6 +43,7 @@ public abstract class CollectionTests : Gee.TestCase {
                add_test ("[Collection] retain_all", test_retain_all);
                add_test ("[Collection] to_array", test_to_array);
                add_test ("[Collection] GObject properties", test_gobject_properties);
+               add_test ("[Collection] fold", test_to_array);
        }
 
        protected Collection<string> test_collection;
@@ -745,4 +746,20 @@ public abstract class CollectionTests : Gee.TestCase {
                assert (value.get_int () == test_collection.size);
                value.unset ();
        }
+       
+       public void test_fold () {
+               assert (test_collection.add ("one"));
+               assert (test_collection.add ("two"));
+               assert (test_collection.add ("three"));
+               
+               int count;
+               
+               count = test_collection.iterator ().fold<int> ((x, y) => {return y + 1;}, 0);
+               assert (count == 3);
+               
+               Iterator<string> iter = test_collection.iterator ();
+               assert (iter.next ());
+               count = iter.fold<int> ((x, y) => {return y + 1;}, 0);
+               assert (count == 3);
+       }
 }