Guest User

Untitled

a guest
May 24th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. // Code for head, copy, and tail are taken from the book Functional Programming in Java
  2. public static <T> T head(List<T> list) {
  3. if (list.size() == 0) {
  4. throw new IllegalStateException("head of empty list");
  5. }
  6. return list.get(0);
  7. }
  8.  
  9. private static <T> List<T> copy(List<T> ts) {
  10. return new ArrayList<>(ts);
  11. }
  12.  
  13. public static <T> List<T> tail(List<T> list) {
  14. if (list.size() == 0) {
  15. throw new IllegalStateException("tail of empty list");
  16. }
  17. List<T> workList = copy(list);
  18. workList.remove(0);
  19. return Collections.unmodifiableList(workList);
  20. }
  21.  
  22. public static int recusive_sum(List<Integer> x) {
  23. return sum_helper(x, 0);
  24. }
  25.  
  26. private static int sum_helper(List<Integer> x, int accumulator) {
  27. // base case
  28. if (x.isEmpty()) {
  29. return accumulator;
  30. }
  31. // processing logic leading to base case
  32. return sum_helper(tail(x), accumulator + head(x));
  33. }
Add Comment
Please, Sign In to add comment