Skip to content

Instantly share code, notes, and snippets.

@nimatrueway
Last active December 19, 2019 15:33
Show Gist options
  • Save nimatrueway/4f4e5ae2476e69515a7427cacf56a639 to your computer and use it in GitHub Desktop.
Save nimatrueway/4f4e5ae2476e69515a7427cacf56a639 to your computer and use it in GitHub Desktop.
mapAccumLeft written in Kotlin
fun <E1, E2, R> mapAccumLeft(list: List<E1>, zero: R, accumulateAndMap: (R, E1) -> Pair<R, E2>): Pair<R, List<E2>> {
return list.fold(Pair(zero, mutableListOf<E2>())) {
(acc, mappedList), elem1 ->
val (newAcc, elem2) = accumulateAndMap(acc, elem1)
Pair(newAcc, mappedList.also { it.add(elem2) })
}
}
// sample usage
mapAccumLeft(listOf(1, 2, 3, 4), "A", { str, num -> Pair(str + num, num * 10) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment