1 package net.sf.jga.fn.algorithm; 33 34 import java.util.Iterator ; 35 import net.sf.jga.fn.BinaryFunctor; 36 import net.sf.jga.fn.UnaryFunctor; 37 38 57 58 public class Accumulate<T> extends UnaryFunctor<Iterator <? extends T>, T> { 59 60 static final long serialVersionUID = 4611344190624502921L; 61 62 private BinaryFunctor<T,T,T> _fn; 64 65 private T _value; 67 68 private boolean _givenValue = false; 70 71 76 public Accumulate(BinaryFunctor<T,T,T> fn) { 77 if (fn == null) 78 throw new IllegalArgumentException (); 79 80 _fn = fn; 81 } 82 83 88 public Accumulate(T startValue, BinaryFunctor<T,T,T> fn){ 89 this(fn); 90 _value = startValue; 91 _givenValue = true; 92 } 93 94 97 public BinaryFunctor<T,T,T> getFunction() { 98 return _fn; 99 } 100 101 104 105 public T getStartValue() { return _value; } 106 107 110 111 public boolean hasStartValue() { return _givenValue; } 112 113 119 public T fn(Iterator <? extends T> iterator) { 120 T value = _givenValue ? _value : 121 iterator.hasNext() ? iterator.next() : null; 122 123 while (iterator.hasNext()) { 124 value = _fn.fn(value, iterator.next()); 125 } 126 127 return value; 128 } 129 130 134 public void accept(net.sf.jga.fn.Visitor v) { 135 if (v instanceof Accumulate.Visitor) 136 ((Accumulate.Visitor)v).visit(this); 137 else 138 v.visit(this); 139 } 140 141 143 public String toString() { 144 return "Accumulate"; 145 } 146 147 149 152 public interface Visitor extends net.sf.jga.fn.Visitor { 153 public void visit(Accumulate host); 154 } 155 } 156 | Popular Tags |