https://kotlinlang.org logo
#announcements
Title
# announcements
x

Xavier F. Gouchet

12/06/2019, 12:17 PM
Hey, I have a list of Strings, and a list of lambdas that convert String to String. Is there a way to apply all lambdas sequentially to all the Strings in the list ? eg:
Copy code
val transforms = listOf<(String) -> String>(
    { it.toLowerCase() },
    { it.split(",").first() }
)
val data = listOf("foo, 42", "BAR, 33")

val result = data.mapAll(transforms) // result has ["foo", "bar"]
k

karelpeeters

12/06/2019, 12:23 PM
`fold`:
Copy code
val result = data.map { transforms.fold(it) { a, t -> t(a) } }
4
x

Xavier F. Gouchet

12/06/2019, 12:25 PM
Thanks @karelpeeters
a

adimit

12/06/2019, 1:29 PM
Another way of looking at it: you're looking for
zip
. Zippers can merge two lists. Typically into a list of pairs, but you can also zip with a function. In your case, the function you'd zip with is simply function application. So your example is:
Copy code
listOf<(String) -> String> { it.toLowerCase() }.zip(listOf("FOO", "BAR")) { f, s -> f(s) }
🤦‍♂️ 1
k

karelpeeters

12/06/2019, 1:30 PM
No that would apply each function to the corresponding string, but he wants to apply each function to all strings.
👍 3
a

adimit

12/06/2019, 1:30 PM
Ah, true. To all the strings in turn. Sorry, I've missed that. Yes, then you need a fold.