I want to split a list (as if splitting a string by a delimiter), ideally in a functional style, and was surprised how hard it seems to be. Or maybe my code is just unnecessarily complicated?
fun <ElemType : Comparable<ElemType>> Iterable<ElemType>.split(delim: ElemType):
List<List<ElemType>> {
return this.fold(emptyList<List<ElemType>>()) {
acc: List<List<ElemType>>, elem: ElemType ->
if (elem == delim)
acc + listOf(emptyList<ElemType>())
else if (acc.isEmpty())
listOf<List<ElemType>>(listOf<ElemType>(elem))
else
acc.take(acc.size - 1) + listOf(acc.last() + elem)
}
}
fun main() {
val l = listOf("1", "", "2", "3", "", "", "4")
println(l.split(""))
val l2 = listOf(1, 0, 2, 3, 0, 0, 4)
println(l2.split(0))
}
The result for both cases is [[1], [2, 3], [], [4]]
.