Functional Programming: Returning list with Fold

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.

Just replace

with

            if (predicate(a)) {
                acc.add(a)
            } 
            acc

2 Likes

Oh my god. It’s that simple? I was trying to apply .toList and so on, but it didn’t work.
But now the code works as intended.
Thank you very much. You helped me alot.