Skip to content

Instantly share code, notes, and snippets.

@andrewharmellaw
Created March 12, 2020 14:48
Show Gist options
  • Save andrewharmellaw/e54d301d31bf49b1615ac6a4ea830944 to your computer and use it in GitHub Desktop.
Save andrewharmellaw/e54d301d31bf49b1615ac6a4ea830944 to your computer and use it in GitHub Desktop.
Three flavours of Kotlin fold...
fun <A, B> foldLeft(l: List<A>,
seed: B,
func: (b: B, a: A) -> B) : B {
return when {
l.isEmpty() -> seed
else -> foldLeft(l.tail, func(seed, l.head), func)
}
}
fun <A, B> foldRightOverflows(l: List<A>,
seed: B,
func: (a: A, b: B) -> B) : B {
return when {
l.isEmpty() -> seed
else -> func(l.head, foldRightOverflows(l.tail, seed, func))
}
}
fun <T> foldRight(l: List<T>,
seed: T,
func: (a: T, b: T) -> T) : T {
return foldLeft(l.asReversed(), seed, func)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment