Skip to content

Instantly share code, notes, and snippets.

@pysaumont
Created February 20, 2017 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pysaumont/c1b387c83f6e377984c50dadb6c867e6 to your computer and use it in GitHub Desktop.
Save pysaumont/c1b387c83f6e377984c50dadb6c867e6 to your computer and use it in GitHub Desktop.
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