added support for fold() along with a handy expect() test method (like scalatest)

This commit is contained in:
James Strachan
2012-01-06 09:35:44 +00:00
parent 16b617044c
commit 4627738ca4
3 changed files with 38 additions and 0 deletions
+14
View File
@@ -81,6 +81,20 @@ inline fun <T> java.lang.Iterable<T>.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 <T> java.lang.Iterable<T>.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