Greg Hibberd
11/18/2019, 11:09 PMJannis
11/18/2019, 11:27 PMList<Option<A>>
unless you really need it, just remove the elements if you don't need them, option makes this much weirder.
Also use maps here if possible! The right data-structure at the right time makes things much easier. (Edit: Nvm I see that the list can contain the same thing multiple times)
Now to the functionality itself:
I get the confusion with the mutable list, quite problematic that you need structural changes inside a map. But I'd invert this: Instead of mapping over testList
, why not fold over toBeRemoved
? I'll write something up in a sec, dunno if my idea will workJannis
11/18/2019, 11:31 PMtestList
is expected to be List<Pair>
and not List<Option<Pair>>
Greg Hibberd
11/18/2019, 11:34 PMOption
to keep it concise. However it's necessary as empty spaces need to be represented tooJannis
11/18/2019, 11:35 PMJannis
11/18/2019, 11:48 PMJannis
11/19/2019, 12:01 AMJannis
11/19/2019, 12:02 AMJannis
11/19/2019, 12:08 AMkotlin
val actual1 = testList.foldLeft(toBeRemoved.toMap() to emptyList<Option<Pair<String, Int>>>()) { (tbR, xs), x ->
x.fold({ tbR to xs + x }, { (k, v) ->
if (tbR.containsKey(k)) tbR[k]!!.let { value ->
val rem = if (value > v) v else value
val newTbR = tbR.mapValues { (key, v) -> if (k == key) v - rem else v }
if (v - rem <= 0) newTbR to xs + None
else newTbR to xs + (k to v - rem).some()
} else tbR to xs + x
})
}.second
Without mutability, could be cleaner with traverse
over State<Map<String, Int>>
Jannis
11/19/2019, 12:09 AMJannis
11/19/2019, 12:11 AMJannis
11/19/2019, 12:11 AMGreg Hibberd
11/19/2019, 12:17 AMtoBeRemoved
id e.g arrayOf(1, 1)
and then map the original list and subtract using the index. That way the only mutation is of a local variable to keep track of how much is left to be removed. Thoughts?Greg Hibberd
11/19/2019, 12:18 AMJannis
11/19/2019, 12:37 AMJannis
11/19/2019, 12:43 AMGreg Hibberd
11/19/2019, 12:47 AM