given a list of String with the following content,...
# stdlib
r
given a list of String with the following content, what is a idiomatic way to split the list into sublists according to this example?
Copy code
val l = listOf(”P”, ”s”, ”P”, ”s”, ”s”, ”P”, ”P”, ”s”)

l.foo() -> [[”P”, ”s”], [”P”, ”s”, ”s”], [”P”], [”P”, ”s”]]
m
Not perfect, but my best idea:
Copy code
fun List<String>.foo(): List<List<String>> = this
    .fold(emptyList<List<String>>()) { acc, v ->
        if (v == "s") acc.dropLast(1) + listOf(acc.lastOrNull().orEmpty() + v)
        else acc + listOf(mutableListOf(v))
    }
🏌️ 1
n
Copy code
fun <T> List<T>.chunkedAt(selector: (T) -> Boolean): List<List<T>> =
    fold(mutableListOf(mutableListOf<T>())) { acc, item ->
        if (selector(item) && acc.last().isNotEmpty()) {
            acc.add(mutableListOf<T>())
        }
        acc.last().add(item)
        acc
    }
    
fun List<String>.foo() = chunkedAt { it.firstOrNull()?.isUpperCase() ?: false }
🏌️ 1
BTW: more a "getting-started" than "stdlib" question