Search code examples
javarecursionstack-overflow

Stack overflow error trying to Binary Fold Left in Java


I'm getting a stack overflow error when attempting to run this code. Can someone please help me debug it?

static <U> U binFoldLeft(U e, List<U>l, BiFunction<U,U,U> f){
    U result = e;

    f.apply(binFoldLeft(result, (l.subList(0, l.size()/2)), f),                 
            binFoldLeft(result, (l.subList(l.size()/2, l.size())),f)); 
    return result;
}

Thanks!


Solution

  • You're missing the base case to end the recursion. As written, binFoldLeft always calls itself twice, even if l is empty.