package fpeas.util; import fpeas.function.Function; import static fpeas.function.FunctionUtility.identity; import fpeas.maybe.Maybe; import static fpeas.maybe.MaybeUtility.fromNullable; import fpeas.pair.Pair; import static fpeas.pair.PairUtility.pair; import java.util.Iterator; import java.util.NoSuchElementException; public class Collections { private static final Function,Integer> min=new Function,Integer>() { public Integer run(final Pair pair) { return Math.min(pair.first(),pair.second()); } }; public static R forEach(final Iterable iterable, final Function function, final Function,R> operator, final R reserve) { R result=reserve; boolean first=true; for (final T t: iterable) { if (first) result=function.run(t); else result=operator.run(pair(result,function.run(t))); first=false; } return result; } public static Maybe min(final Iterable iterable) { final Function identity=identity(); return fromNullable(forEach(iterable,identity,min,null)); } public static Iterable filter(final Iterable iterable,final Function condition) { return new Iterable() { public Iterator iterator() { final Iterator wrapped=iterable.iterator(); return new Iterator() { private T next; public boolean hasNext() { if (next!=null) return true; while (wrapped.hasNext()) { final T possibleNext=wrapped.next(); if (condition.run(possibleNext)) { next=possibleNext; return true; } } return false; } public T next() { if (next!=null) { final T tempNext=next; next=null; return tempNext; } while (wrapped.hasNext()) { final T possibleNext=wrapped.next(); if (condition.run(possibleNext)) return possibleNext; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } }; } }; } }