From 4627738ca4c745fd6b0acc1d410c5da19a4838c2 Mon Sep 17 00:00:00 2001 From: James Strachan Date: Fri, 6 Jan 2012 09:35:44 +0000 Subject: [PATCH] added support for fold() along with a handy expect() test method (like scalatest) --- stdlib/ktSrc/JavaIterables.kt | 14 ++++++++++++++ testlib/test/CollectionTest.kt | 15 +++++++++++++++ testlib/test/Test.kt | 9 +++++++++ 3 files changed, 38 insertions(+) diff --git a/stdlib/ktSrc/JavaIterables.kt b/stdlib/ktSrc/JavaIterables.kt index e209250b1fc..f6996b7d989 100644 --- a/stdlib/ktSrc/JavaIterables.kt +++ b/stdlib/ktSrc/JavaIterables.kt @@ -81,6 +81,20 @@ inline fun java.lang.Iterable.foreach(operation: (element: T) -> Unit) { operation(elem) } +/** + * Folds all the values from from left to right using the initial value to perform the operation on sequential pairs of values + * + * For example to sum together all numeric values in a collection of numbers it would be + * {code}numbers.fold(0){(a, b) -> a + b}{code} + */ +inline fun java.lang.Iterable.fold(initial: T, operation: (it: T, it2: T) -> T): T { + var answer = initial + for (elem in this) { + answer = operation(answer, elem) + } + return answer +} + /** * Iterates through the collection performing the transformation on each element and using the result * as the key in a map to group elements by the result diff --git a/testlib/test/CollectionTest.kt b/testlib/test/CollectionTest.kt index ec001fc66bd..bf570281b2c 100644 --- a/testlib/test/CollectionTest.kt +++ b/testlib/test/CollectionTest.kt @@ -127,6 +127,21 @@ class CollectionTest() : TestSupport() { assertEquals(6, count) } + fun testFold() { + expect(10) { + val numbers = arrayList(1, 2, 3, 4) + + // TODO would be nice to be able to write this as this + //numbers.fold(0){it + it2} + numbers.fold(0){(it, it2) -> it + it2} + } + + expect(0) { + val numbers = arrayList() + numbers.fold(0){(it, it2) -> it + it2} + } + } + fun testGroupBy() { val words = arrayList("a", "ab", "abc", "def", "abcd") /* diff --git a/testlib/test/Test.kt b/testlib/test/Test.kt index 25620696712..ecac22b3faa 100644 --- a/testlib/test/Test.kt +++ b/testlib/test/Test.kt @@ -97,6 +97,15 @@ fun assertNull(actual: Any?, message: String = "") { Assert.assertNull(message, actual) } +fun expect(expected: T, block: ()-> T) { + expect(expected, block.toString(), block) +} + +fun expect(expected: T, message: String, block: ()-> T) { + val actual = block() + assertEquals(expected, actual, message) +} + fun fails(block: ()-> Any) { try { block()