Functional Programming in Java: How functional techniques improve your Java programs by Pierre-Yves Saumont

Functional Programming in Java: How functional techniques improve your Java programs by Pierre-Yves Saumont

Author:Pierre-Yves Saumont
Language: eng
Format: mobi, epub
Publisher: Manning Publications
Published: 2017-02-02T15:09:21.809000+00:00


Is it possible to do it with a fold? Right or left?

Why is the explicit recursive version better?

Can you see a way to solve the problem?

Solution 8.12

The explicitly recursive solution is easy:

public Result<A> getAt(int index) {

return index < 0 || index >= length()

? Result.failure("Index out of bound")

: getAt_(this, index).eval();

}

private static <A> TailCall<Result<A>> getAt_(List<A> list, int index) {

return index == 0

? TailCall.ret(Result.success(list.head()))

: TailCall.sus(() -> getAt_(list.tail(), index - 1));

}

First, you can check the index to see if it’s positive and less than the list length. If it isn’t, just return a Failure. Otherwise, call the helper method to process the list recursively. This method checks whether the index is 0. If it is, it returns the head of the list. Otherwise, it calls itself recursively on the tail of the list with a decremented index.

This looks like the best possible recursive solution. Is it possible to use a fold? Yes, it is, and it should be a left fold. But the solution is tricky:

public Result<A> getAt(int index) {

Tuple<Result<A>, Integer> identity =

new Tuple<>(Result.failure("Index out of bound"), index);



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.