concept tail in category functional programming

appears as: tail, tail, tails
Functional Programming in Java: How functional techniques improve your Java programs

This is an excerpt from Manning's book Functional Programming in Java: How functional techniques improve your Java programs.

3.3.3. Using head and tail operations

Functional operations on lists often access the head (or first element) of the list, as well as the tail (the list with its first element removed).

The tail method is slightly more complex. It must make a copy of its argument, remove the first element, and return the result:

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);
}

Note that copy is private. It returns a mutable list. To make a copy from the outside, you can call list(List<T>), which returns an immutable list. Also note that this example throws exceptions when calling head or tail on an empty list. This isn’t functional, because you should always catch exceptions but never throw them in order to be referentially transparent. It is, however, simpler at this stage. In chapter 5, when you look at functional lists, you’ll see that the head and tail methods will be declared protected. This way, they’ll be usable only inside the List class, and no exception will ever leak out of this class.