Home > Enterprise >  Intersection of several lists with reduce
Intersection of several lists with reduce

Time:12-12

I wanted to create a function that returns an intersection of several lists. I did something like this:

fun <T> List<List<T>>.intersection(): List<T> {
    return this.reduce { acc, it -> acc.apply { acc.toMutableSet().retainAll(it.toSet()) } }
}

I called it with List<List<Int>> like this [[12, 321], [4, 35, 4], [67, 57, 8], [98, 97]], but it keeps returning me the first list. The expected list should be an empty list. I added an also to see what this reduce is called with and it is the same (the first one) list all the time. Can someone explain what I'm doing wrong here and how can I write that function with reduce?

CodePudding user response:

Your code currently creates a copy of acc as a mutable set, removes the elements not in it, and then does nothing with it. You never actually save or return the results. acc.apply only reflects modifications actually made to acc, not anything you did with copies of acc.

  • Related