I have a data class like this:
data class Protein(val id: String, val score: Double, val molw: Double, val spc: Int) {
override fun hashCode() = id.hashCode()
override fun equals(other: Any?) = other?.let { id == (it as Protein).id } ?: false
}
As per another question I asked, I now have a function that can reduce an ArrayList of HashSets with Proteins
fun intersection(data: ArrayList<HashSet<Protein>>): HashSet<Protein> {
return data.reduce { acc, it -> acc.retainAll(it); acc }
}
What I want to do is take a subset of the original ArrayList and return a reduced version. So I tried to do this:
fun intersection(data: ArrayList<HashSet<Protein>>, combination: List<Int>): HashSet<Protein> {
val newdata = ArrayList<HashSet<Protein>>()
for (entry in combination) {
newdata.add(data[entry-1]) }
return newdata.reduce { acc, it -> acc.retainAll(it); acc } }
Combination tells the function which entries to take from the data ArrayList (eg 1,2,4). The size of the newdata ArrayList will always be 3 (checked this too).
When I run the raw data (ArrayList of 6) through the first intersection function, it reduces just fine. When I run the same data through the second function, it returns a map error, saying that the Key is not found.
I have a feeling this has something to do with the override function for the Protein data class, but I can't find anything about how to work with functional programming for reduce...
I simplified the code a bit and got the following:
fun intersection(data: List<HashSet<Protein>>) =
data.reduce { acc, it -> acc.apply { retainAll(it) } }
fun intersection(data: List<HashSet<Protein>>, combination: List<Int>) =
intersection(combination.map { data[it - 1] })
I was able to get the expected result with:
val s1 = hashSetOf(Protein("1",2.0, 2.0,1), Protein("2",2.0, 2.0,1))
val s2 = hashSetOf(Protein("3",2.0, 2.0,1), Protein("2",2.0, 2.0,1))
val s3 = hashSetOf(Protein("3",2.0, 2.0,1), Protein("4",2.0, 2.0,1))
println(intersection(listOf(s1,s2,s3), listOf(1,2))) //[Protein(id=2, score=2.0, molw=2.0, spc=1)]
So no error occurred. Can you please provide your test code?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With