Created
July 4, 2017 14:51
-
-
Save sitepodmatt/c286ebf3f71f8f6d0d5335ae3f947667 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main(args: Array<String>) { | |
println("Foldwhile experiment") | |
val oneTo100 = 1 until 100 | |
println(oneTo100.fold(0) { acc, v -> acc + v}) | |
println("Stop folding when total is above 2000") | |
println(oneTo100.foldWhile(0, { acc, v -> acc + v }, { acc, _ -> acc < 2000 })) | |
} | |
private fun <T, V> Iterable<T>.foldWhile(initial: V, operation: (V, T) -> V, predicate: (V,T) -> Boolean) : V { | |
return this.fold(initial) { acc, v -> | |
if(predicate(acc, v)) { | |
operation(acc, v) | |
} else { | |
return acc | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment