The
List class is a singly linked list I present in the book. The list method is simply a constructor function (not a Java constructor, rather a factory method in legacy Java terms). This method should be named
unit (or
return, but this is not possible in Java) to respect the functional terminology, but I generally prefer to call unit methods by the name of the class with a lowercase initial, which is compatible with static import. In Scala, such methods are named
apply but the language offers syntactic sugar to call them using the name of the class, such as List(1, 13, 42, 7, 37).
Implementing this method in a functional way in Java is tricky. I show a functional implementation in the book, but it is awfully slow. Of course, an imperative implementation (using a loop and mutable variables) is perfectly correct, as long as the method respects referential transparency. A functional implementation would be one using no mutation. It would be difficult not use mutable object, since the argument itself is mutable, but one should not mutate it. A (non functional implementation) could be:
where NIL is a singleton of Nil which is one of the sub classes of List, representing the empty list. Cons is the other sub class representing a non empty list. It is basically:
The real (even less functional) implementation is:
A functional implementation (without using mutation) is possible (using stack safe recursion as I explained in another post):
It has the only (minimal!) inconvenient to be much much slower! (And this is not due to recursion!).
But as I already said, a functional library does not have to have a 100% functional implementation. It only has to offer a 100% functional interface.
By the way, the full List class is available on the
FP in java book code github site