How could I design the following code in a more fu...
# announcements
p
How could I design the following code in a more functional, immutable way? There's a single string where I want to throw multiple regexes on it. The size of the list of regex is flexible, so I can't operate over a set range. I'm actually refactoring some guys code and it grinds my gears that I cannot come up with a simpler solution for that:
Copy code
var label = when {
    ..someConditions.. -> "someString"
    else -> ""
}

regexes.forEach {
    label = label.replace(it.toRegex(), "").trim()
}

return label
I should maybe just step away from it for some time.. 😄 any hint is appreciated, thanks!
e
Copy code
label = regexes.fold(label) { label, regex -> label.replace(regex, "") }
👍 3
☝️ 1
n
any
Copy code
list.forEach {
    x = f(x)
}
is often best modeled as a fold/reduce-type thing. only exception is probably if you're working with collections...List#add makes a copy each time, which can have atrocious performance, so gotta watch out for that.
e
in which case you can use a
.mapTo()
🙂
j
@nanodeath @ephemient can you give a brief example of the problem and solution? This reminds me of a day back in Java 101 but I can't seem to recall the rest of the lesson 🤣
n
the problem is "how do I avoid using var when applying a list of operations to a value"
and the solution is to fold over the list
j
Sorry, the
List#add
performance issue
n
ah
tbh I didn't follow the
mapTo
suggestion
e
instead of or
val result = list.fold(listOf()) { result, it -> result + it }
or
val result = mutableListOf(); list.forEach { result.add(f(it)) }
use
list.mapTo(result) { f(it) }
well, of course in a simple case like this you could just use
.map()
, but in general
.mapTo()
has its uses too
j
Is the issue with
ArrayList#add
that it creates a new array under the hood each time?
e
yes, exactly
p
Thanks for your help! Finally a good point to start looking into fold. I was always wondering what a usecase for it could be.
m
you have a use for fold() any time you need to apply some function to a list to compute a single value out of it