The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

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()