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

NonEmpty.java (1706B)


      1 import java.util.Objects;
      2 import java.util.function.BiFunction;
      3 import java.util.function.Function;
      4 import java.util.function.Predicate;
      5 
      6 public class NonEmpty<V> implements Cons<V> {
      7 
      8     private final V first;
      9     private final Cons<V> rest;
     10 
     11     public NonEmpty(V first, Cons<V> rest) {
     12         this.first = first;
     13         this.rest = rest;
     14     }
     15 
     16     @Override
     17     public V first() {
     18         return first;
     19     }
     20 
     21     @Override
     22     public Cons<V> rest() {
     23         return rest;
     24     }
     25 
     26     @Override
     27     public <W> Cons<W> map(Function<V, W> mapper) {
     28         return new NonEmpty<>(mapper.apply(first), rest.map(mapper));
     29     }
     30 
     31     @Override
     32     public Cons<V> filter(Predicate<V> predicate) {
     33         var newRest = rest.filter(predicate);
     34         return predicate.test(first) ?
     35             new NonEmpty<>(first, newRest) :
     36             newRest;
     37     }
     38 
     39     @Override
     40     public <W> W foldl(BiFunction<V, W, W> f, W init) {
     41         var newInit = f.apply(first, init);
     42         return rest.foldl(f, newInit);
     43     }
     44 
     45     @Override
     46     public <W> W foldr(BiFunction<V, W, W> f, W init) {
     47         var value = rest.foldr(f, init);
     48         return f.apply(first, value);
     49     }
     50 
     51     @Override
     52     public boolean empty() {
     53         return false;
     54     }
     55 
     56     @Override
     57     public boolean equals(Object o) {
     58         if (this == o) return true;
     59         if (!(o instanceof Cons)) return false;
     60         Cons<?> cons = (Cons<?>) o;
     61         return Objects.equals(first, cons.first()) && Objects.equals(rest, cons.rest());
     62     }
     63 
     64     @Override
     65     public int hashCode() {
     66         return Objects.hash(first, rest);
     67     }
     68 
     69     @Override
     70     public String toString() {
     71         return "(cons " + first + " " + rest + ")";
     72     }
     73 }