[libgee] Add Iterator.fold aggregative function



commit 25ecf4f95859b68a4207861ee0655e2cea85be3e
Author: Maciej Piechotka <uzytkownik2 gmail com>
Date:   Sun Oct 17 17:14:59 2010 +0100

    Add Iterator.fold aggregative function

 gee/iterator.vala         |   22 ++++++++++++++++++++++
 tests/testcollection.vala |   17 +++++++++++++++++
 2 files changed, 39 insertions(+), 0 deletions(-)
---
diff --git a/gee/iterator.vala b/gee/iterator.vala
index 3b09d63..48c749e 100644
--- a/gee/iterator.vala
+++ b/gee/iterator.vala
@@ -23,6 +23,10 @@
  * 	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;
+	}
 }
 
diff --git a/tests/testcollection.vala b/tests/testcollection.vala
index 06d5d94..0f2be80 100644
--- a/tests/testcollection.vala
+++ b/tests/testcollection.vala
@@ -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);
+	}
 }



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]