/** * Copyright (c): Uwe Schmidt, FH Wedel * * You may study, modify and distribute this source code * FOR NON-COMMERCIAL PURPOSES ONLY. * This copyright message has to remain unchanged. * * Note that this document is provided 'as is', * WITHOUT WARRANTY of any kind either expressed or implied. */ package ds.util; /** This iterator supports a few more operation than the java.util one. These operations can be used by all classes supporting the Iterator interface and give us generally applicable operations for a lot of containers. These iterators have much in common with lazy list in Haskell .1 The remove operation, which is a wart, always raises an execpton. .2 An iterator can show it's elements. So we have a show method for all classes supporting ds.util.Iterator. .3 An iterator can count it's elements. Same advantage as in .2 .4 An iterator can fold it's elements, this corresponds to a Haskell foldl. .5 An iterator can build a new iterator with all elements processed element wise by a unary function, corresponds to Haskell map. */ public abstract class Iterator implements java.util.Iterator { /** get rid of repeated implementations of unsupported operation remove */ public void remove() { throw new UnsupportedOperationException ("iterator does not support remove"); } /** An iterator can count it's elements. */ public int size() { int res = 0; while ( hasNext() ) { ++res; next(); } return res; } /** An iterator can fold it's elements, a generalisation of size */ public R fold(R n, Function2 f) { R res = n; while ( hasNext() ) { E x = next(); res = f.apply(res, x); } return res; } /** An iterator can generate a another iterator containig all elements processed by a unary function */ public Iterator map(Function f) { return new MapIterator(this, f); } /** All quantifier for iterators */ public boolean all(Predicate p) { boolean res = true; while ( res && hasNext() ) { res = p.isTrue(next()); } return res; } /** Any quantifier for iterators */ public boolean any(Predicate p) { boolean res = false; while ( ! res && hasNext() ) { res = p.isTrue(next()); } return res; } /** An iterator can show itself, but afterwards it becomes useless, all elements are already consumed */ public String toString() { StringBuffer res = new StringBuffer(); if ( hasNext() ) { boolean first = true; while ( hasNext() ) { E x = next(); res.append(first ? "[" : ","); res.append(x); first = false; } } else { res.append("["); } res.append("]"); return new String(res); } }