Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Code for head, copy, and tail are taken from the book Functional Programming in Java
- public static <T> T head(List<T> list) {
- if (list.size() == 0) {
- throw new IllegalStateException("head of empty list");
- }
- return list.get(0);
- }
- private static <T> List<T> copy(List<T> ts) {
- return new ArrayList<>(ts);
- }
- public static <T> List<T> tail(List<T> list) {
- if (list.size() == 0) {
- throw new IllegalStateException("tail of empty list");
- }
- List<T> workList = copy(list);
- workList.remove(0);
- return Collections.unmodifiableList(workList);
- }
- public static int recusive_sum(List<Integer> x) {
- return sum_helper(x, 0);
- }
- private static int sum_helper(List<Integer> x, int accumulator) {
- // base case
- if (x.isEmpty()) {
- return accumulator;
- }
- // processing logic leading to base case
- return sum_helper(tail(x), accumulator + head(x));
- }
Add Comment
Please, Sign In to add comment