java-cons

This small, one interface project is a try to reimplement the mechanics used in Rackets cons cells in Java.
git clone git://git.oshgnacknak.de/java-cons.git
Log | Files | Refs | README

Cons.java (684B)


      1 import java.util.function.BiFunction;
      2 import java.util.function.Function;
      3 import java.util.function.Predicate;
      4 
      5 public interface Cons<V> {
      6 
      7     V first();
      8 
      9     Cons<V> rest();
     10 
     11     <W> Cons<W> map(Function<V, W> mapper);
     12 
     13     Cons<V> filter(Predicate<V> predicate);
     14 
     15     <W> W foldl(BiFunction<V, W, W> f, W init);
     16 
     17     <W> W foldr(BiFunction<V, W, W> f, W init);
     18 
     19     boolean empty();
     20 
     21     @SafeVarargs
     22     static <V> Cons<V> of(V... arr) {
     23         return fromArray(0, arr);
     24     }
     25 
     26     private static <V> Cons<V> fromArray(int n, V[] arr) {
     27         if (n >= arr.length) {
     28             return new Empty<>();
     29         }
     30         return new NonEmpty<>(arr[n], fromArray(n+1, arr));
     31     }
     32 }