Skip to content

Instantly share code, notes, and snippets.

@sitepodmatt
Created July 4, 2017 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sitepodmatt/c286ebf3f71f8f6d0d5335ae3f947667 to your computer and use it in GitHub Desktop.
Save sitepodmatt/c286ebf3f71f8f6d0d5335ae3f947667 to your computer and use it in GitHub Desktop.
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