Functional Programming in Kotlin: Counting elements in list by using fold

Solution 1:

By saying return you return the entire count function. you can use return@fold instead. so like

fun <A> count(list: List<A>, predicate: (A) -> Boolean): Int {
    return list.fold(0) {
            acc, a ->
        if (predicate(a)) {
            return@fold acc + 1
        }

        return@fold  acc
    }
}

alternatively and maybe better is to do it like this

fun <A> count(list: List<A>, predicate: (A) -> Boolean): Int {
    return list.fold(0) {
            acc, a ->
        if (predicate(a)) {
            acc + 1
        } else {
            acc
        }
    }
}

the last expression in a lambda is implicitly also its return value

Solution 2:

Try it like this:

fun <A> count(list: List<A>, predicate: (A) -> Boolean): Int {
    return list.fold(0) { acc, a -> if (predicate(a)) acc+1 else acc }
}

fun main(args: Array<String>) {
    val x = listOf<Int>( 1, -2, 3, 10, -5, 8, 12);
    println(count(x, { it > 0 && it < 10 }))
}

Looking at this site made the necessary change clear to me.

Is that form necessary because fold uses tail recursion? Interesting to see what the reason is.