I suspect you're confusing the reduce()
function with the fold()
function.
Both are higher-order functions which apply an operation consecutively to values in a list (or array) to combine them into a single result.
reduce()
is the simpler function, in which the final result is the same type as the list elements. This means that the operation must take two values of the same type, and return a value of that same type.* For example, you could add up list of integers by calling reduce()
on it and giving addition function — one which adds two integers to give another integer, so the partial sums and the final sum are integers too.
fold()
is a more general function, in which the final result can be an unrelated type. This makes it more powerful, but also a little more complex. The operation you give must take one parameter of the list type, but another (the accumulator) of the result type, and it must return the result type. And because it can't ‘bootstrap’ in the same way as reduce()
, you also need to give an initial value for the accumulator (e.g. 0 for addition).
In your case, I'm not entirely sure what you're trying to achieve (other than learning about higher-order functions, which is of course a perfectly valid goal!), so I don't have a `solution’ as such.
Your list contains functions, so a reduce()
would have to return a function as well. This is possible, but combining functions to give another function is complex, e.g.:
val res = funcs.reduce{ acc, elem -> { i -> elem(i) + acc(i) } }
However, a fold()
would also work [as, I see from your edit, you've discovered] and would seem closer to your aim:
val res = funcs.fold(0){ acc, elem -> elem(1) + acc }
(* Actually, the result type of reduce()
can be a supertype of the element type, as you can see from the signature: inline fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S
. But it can't be an unrelated type.)