Greetings,
I’ve got the task to write a function using fold (functional programming) to filter elements in a list. The elements that fulfill the predicate shall be put in a new list. I was given the function signature fun <A> filter(list: List<A>, predicate: (A) -> Boolean): List<A>
. Fold shall not only be used as iteration, but also generate the return value (list). So I tried to do this:
fun <A> filter(list: List<A>, predicate: (A) -> Boolean): List<A> {
return list.fold<A, MutableList<A>>(mutableListOf()) {
acc, a ->
if (predicate(a)) {
acc.add(a)
} else {
acc
}
}
}
The problem that I found is that acc.add(a)
returns a boolean and not a list, so that the IDE marks it as a mistake. So is there a way to return a list?
Thanks in Advance.