356497 (4) [Avatar] Offline
#1
Hi
just a quick question as i am littlebit puzzled regarding foldLeft and foldRight
so, pls correct me if i m wrong, foldRight is implemented 'roughly' like this , in a recursive fashion - pls correct me if i m wrong -

private static <T,U> U foldRight(List<T> inputList, U identity, Function<T, Function<U, U>> foldFunction) {

return inputList.isEmpty() ?
identity:
foldFunction.apply(last(inputList)).apply(foldRight(init(inputList), identity, foldFunction));

}

now, out of curiosity.... any particular reason why a 'fold left'-like foldright cannot be implemented?

private static <T,U> U foldRightCorecursive(List<T> inputList, U identity, Function<T, Function<U, U>> foldFunction) {

return inputList.isEmpty() ?
identity:
foldRightCorecursive(init(inputList), foldFunction.apply(last(inputList)).apply(identity), foldFunction);
}


Is it because the way foldRight shoud behave?
Am i missing something?

Pierre could you pls comment ?

once again, great book , really enjoing going thru it

Pls note that init() will return a new list which excludes the last element, and last returns the last element. i didnt provide these functions in the snippet


kr



356497 (4) [Avatar] Offline
#2
got the answer myself
with my static append/tail/etc i was bypassing the immutable list implementation in the book, which only allow to add to the head()