Last active
December 19, 2019 15:33
-
-
Save nimatrueway/4f4e5ae2476e69515a7427cacf56a639 to your computer and use it in GitHub Desktop.
mapAccumLeft written in Kotlin
This file contains hidden or 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 <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