Skip to content

Instantly share code, notes, and snippets.

@ch8n
Created September 3, 2022 18:37
Show Gist options
  • Save ch8n/138acf271249e9d75466ffa30abe91f0 to your computer and use it in GitHub Desktop.
Save ch8n/138acf271249e9d75466ffa30abe91f0 to your computer and use it in GitHub Desktop.
Head Recursion - Kotlin
fun main() {
val list = listOf(1, 2, 3, 4, 5, 6)
list.headRecursion { print(it) }
}
fun <T> List<T>.headRecursion(index: Int = lastIndex, next: (item: T) -> Unit) {
if (index >= 0) {
headRecursion(index - 1, next)
next.invoke(get(index))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment