Created
February 20, 2017 09:49
-
-
Save pysaumont/c1b387c83f6e377984c50dadb6c867e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class List<T> implements Foldable<T>, Appendable<T, List<T>> { | |
private final java.util.List<T> delegate; | |
public List(java.util.List<T> delegate) { | |
this.delegate = delegate; | |
} | |
public int size() { | |
return this.delegate.size(); | |
} | |
@Override | |
public Appendable<T, List<T>> append(T t) { | |
java.util.List<T> result = new ArrayList<>(delegate); | |
result.add(t); | |
return new List<>(result); | |
} | |
@Override | |
public List<T> get() { | |
return this; | |
} | |
@Override | |
public <U> U foldRight(U seed, BiFunction<T, U, U> f) { | |
U result = seed; | |
ListIterator<T> li = delegate.listIterator(delegate.size()); | |
while(li.hasPrevious()) { | |
result = f.apply(li.previous(), result); | |
} | |
return result; | |
} | |
@Override | |
public <U> U foldLeft(U seed, BiFunction<U, T, U> f) { | |
U result = seed; | |
for (T t : delegate) { | |
result = f.apply(result, t); | |
} | |
return result; | |
} | |
@Override | |
public String toString() { | |
return String.format("[%sNIL]", foldRight("", (a, b) -> String.format("%s, %s", a, b))); | |
} | |
@SafeVarargs | |
public static <T> List<T> of(T... ts) { | |
return new List<>(Arrays.asList(ts)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment