package bjc.utils.data; import bjc.utils.data.internals.BoundLazy; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.UnaryOperator; /** * A holder that holds a means to create a value, but doesn't actually compute * the value until it's needed * * @author ben * * @param */ public class Lazy implements IHolder { private Supplier valueSupplier; private IList> actions = new FunctionalList<>(); private boolean valueMaterialized; private ContainedType heldValue; /** * Create a new lazy value from the specified seed value * * @param value * The seed value to use */ public Lazy(ContainedType value) { heldValue = value; valueMaterialized = true; } /** * Create a new lazy value from the specified value source * * @param supp * The source of a value to use */ public Lazy(Supplier supp) { valueSupplier = new SingleSupplier<>(supp); valueMaterialized = false; } private Lazy(Supplier supp, IList> pendingActions) { valueSupplier = supp; actions = pendingActions; } @Override public IHolder bind(Function> binder) { IList> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); Supplier supplier = () -> { if(valueMaterialized) return heldValue; return valueSupplier.get(); }; return new BoundLazy<>(() -> { return new Lazy<>(supplier, pendingActions); }, binder); } @Override public Function> lift(Function func) { return (val) -> { return new Lazy<>(func.apply(val)); }; } @Override public IHolder map(Function mapper) { IList> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); return new Lazy<>(() -> { ContainedType currVal = heldValue; if(!valueMaterialized) { currVal = valueSupplier.get(); } return pendingActions.reduceAux(currVal, UnaryOperator::apply, (value) -> mapper.apply(value)); }); } @Override public String toString() { if(valueMaterialized) { if(actions.isEmpty()) return "value[v='" + heldValue + "']"; return "value[v='" + heldValue + "'] (has pending transforms)"; } return "(unmaterialized)"; } @Override public IHolder transform(UnaryOperator transformer) { actions.add(transformer); return this; } @Override public UnwrappedType unwrap(Function unwrapper) { if(!valueMaterialized) { heldValue = valueSupplier.get(); valueMaterialized = true; } actions.forEach((action) -> { heldValue = action.apply(heldValue); }); actions = new FunctionalList<>(); return unwrapper.apply(heldValue); } }