diff options
Diffstat (limited to 'src')
70 files changed, 1933 insertions, 1535 deletions
diff --git a/src/main/java/bjc/data/ArrayIterator.java b/src/main/java/bjc/data/ArrayIterator.java index 6037e34..6d11a1d 100644 --- a/src/main/java/bjc/data/ArrayIterator.java +++ b/src/main/java/bjc/data/ArrayIterator.java @@ -1,22 +1,24 @@ package bjc.data; import java.util.Iterator; + /** * Represents an iterator over an array of values. * - * @param <T> The type of values in the array. - * + * @param <T> + * The type of values in the array. + * * @author Ben Culkin */ public class ArrayIterator<T> implements Iterator<T> { private Object[] arr; - private int idx; + private int idx; /** * Create a new array iterator. * * @param elms - * The array that will be iterated over. + * The array that will be iterated over. */ @SafeVarargs public ArrayIterator(T... elms) { @@ -32,8 +34,9 @@ public class ArrayIterator<T> implements Iterator<T> { @SuppressWarnings("unchecked") @Override public T next() { - if (idx >= arr.length) return null; + if (idx >= arr.length) + return null; - return (T)(arr[idx++]); + return (T) (arr[idx++]); } } diff --git a/src/main/java/bjc/data/BooleanToggle.java b/src/main/java/bjc/data/BooleanToggle.java index 209e97c..af083f5 100644 --- a/src/main/java/bjc/data/BooleanToggle.java +++ b/src/main/java/bjc/data/BooleanToggle.java @@ -21,7 +21,7 @@ public class BooleanToggle implements Toggle<Boolean> { * Create a flip-flop with the specified initial value. * * @param initial - * The initial value of the flip-flop. + * The initial value of the flip-flop. */ public BooleanToggle(final boolean initial) { val = initial; @@ -59,13 +59,17 @@ public class BooleanToggle implements Toggle<Boolean> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof BooleanToggle)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof BooleanToggle)) + return false; final BooleanToggle other = (BooleanToggle) obj; - if(val != other.val) return false; + if (val != other.val) + return false; return true; } diff --git a/src/main/java/bjc/data/CircularIterator.java b/src/main/java/bjc/data/CircularIterator.java index 6842b26..ce6b4c3 100644 --- a/src/main/java/bjc/data/CircularIterator.java +++ b/src/main/java/bjc/data/CircularIterator.java @@ -8,7 +8,7 @@ import java.util.Iterator; * @author EVE * * @param <E> - * The type of the iterable. + * The type of the iterable. */ public class CircularIterator<E> implements Iterator<E> { /* The iterable, and our current iterator into it. */ @@ -19,8 +19,7 @@ public class CircularIterator<E> implements Iterator<E> { private E curElm; /* - * Should we actually get new iterators, or just repeat the last - * element? + * Should we actually get new iterators, or just repeat the last element? */ private boolean doCircle; @@ -28,11 +27,11 @@ public class CircularIterator<E> implements Iterator<E> { * Create a new circular iterator. * * @param src - * The iterable to iterate from. + * The iterable to iterate from. * * @param circ - * Should we actually do circular iteration, or just - * repeat the terminal element? + * Should we actually do circular iteration, or just repeat the + * terminal element? */ public CircularIterator(final Iterable<E> src, final boolean circ) { source = src; @@ -45,7 +44,7 @@ public class CircularIterator<E> implements Iterator<E> { * Create a new circular iterator that does actual circular iteration. * * @param src - * The iterable to iterate from. + * The iterable to iterate from. */ public CircularIterator(final Iterable<E> src) { this(src, true); @@ -63,7 +62,7 @@ public class CircularIterator<E> implements Iterator<E> { if (!doCircle) { return curElm; } - + curr = source.iterator(); } diff --git a/src/main/java/bjc/data/Either.java b/src/main/java/bjc/data/Either.java index 0588496..55518d8 100644 --- a/src/main/java/bjc/data/Either.java +++ b/src/main/java/bjc/data/Either.java @@ -9,10 +9,10 @@ import java.util.function.Function; * @author ben * * @param <LeftType> - * The type that could be on the left. + * The type that could be on the left. * * @param <RightType> - * The type that could be on the right. + * The type that could be on the right. * */ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @@ -20,17 +20,18 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { * Create a new either with the left value occupied. * * @param <LeftType> - * The type of the left value. + * The type of the left value. * * @param <RightType> - * The type of the empty right value. - * + * The type of the empty right value. + * * @param left - * The value to put on the left. + * The value to put on the left. * * @return An either with the left side occupied. */ - public static <LeftType, RightType> Either<LeftType, RightType> left(final LeftType left) { + public static <LeftType, RightType> Either<LeftType, RightType> + left(final LeftType left) { return new Either<>(left, null); } @@ -38,17 +39,18 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { * Create a new either with the right value occupied. * * @param <LeftType> - * The type of the empty left value. + * The type of the empty left value. * * @param <RightType> - * The type of the right value. + * The type of the right value. * * @param right - * The value to put on the right. + * The value to put on the right. * * @return An either with the right side occupied. */ - public static <LeftType, RightType> Either<LeftType, RightType> right(final RightType right) { + public static <LeftType, RightType> Either<LeftType, RightType> + right(final RightType right) { return new Either<>(null, right); } @@ -61,7 +63,7 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { /* Create a new either with specifed values. */ private Either(final LeftType left, final RightType right) { - if(left == null) { + if (left == null) { rightVal = right; } else { leftVal = left; @@ -73,17 +75,20 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( final BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { - if(binder == null) throw new NullPointerException("Binder must not be null"); + if (binder == null) + throw new NullPointerException("Binder must not be null"); return binder.apply(leftVal, rightVal); } @Override - public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( - final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { - if(leftBinder == null) throw new NullPointerException("Left binder must not be null"); + public <BoundLeft> IPair<BoundLeft, RightType> + bindLeft(final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + if (leftBinder == null) + throw new NullPointerException("Left binder must not be null"); - if(isLeft) return leftBinder.apply(leftVal); + if (isLeft) + return leftBinder.apply(leftVal); return new Either<>(null, rightVal); } @@ -91,27 +96,31 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundRight> IPair<LeftType, BoundRight> bindRight( final Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { - if(rightBinder == null) throw new NullPointerException("Right binder must not be null"); + if (rightBinder == null) + throw new NullPointerException("Right binder must not be null"); - if(isLeft) return new Either<>(leftVal, null); + if (isLeft) + return new Either<>(leftVal, null); return rightBinder.apply(rightVal); } @Override - public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - final IPair<OtherLeft, OtherRight> otherPair, - final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, - final BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { - if(otherPair == null) { + public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> + IPair<CombinedLeft, CombinedRight> + combine(final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<RightType, OtherRight, + CombinedRight> rightCombiner) { + if (otherPair == null) { throw new NullPointerException("Other pair must not be null"); - } else if(leftCombiner == null) { + } else if (leftCombiner == null) { throw new NullPointerException("Left combiner must not be null"); - } else if(rightCombiner == null) { + } else if (rightCombiner == null) { throw new NullPointerException("Right combiner must not be null"); } - if(isLeft) { + if (isLeft) { return otherPair.bind((otherLeft, otherRight) -> { CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); @@ -127,26 +136,34 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { } @Override - public <NewLeft> IPair<NewLeft, RightType> mapLeft(final Function<LeftType, NewLeft> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <NewLeft> IPair<NewLeft, RightType> + mapLeft(final Function<LeftType, NewLeft> mapper) { + if (mapper == null) + throw new NullPointerException("Mapper must not be null"); - if(isLeft) return new Either<>(mapper.apply(leftVal), null); + if (isLeft) + return new Either<>(mapper.apply(leftVal), null); return new Either<>(null, rightVal); } @Override - public <NewRight> IPair<LeftType, NewRight> mapRight(final Function<RightType, NewRight> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <NewRight> IPair<LeftType, NewRight> + mapRight(final Function<RightType, NewRight> mapper) { + if (mapper == null) + throw new NullPointerException("Mapper must not be null"); - if(isLeft) return new Either<>(leftVal, null); + if (isLeft) + return new Either<>(leftVal, null); return new Either<>(null, mapper.apply(rightVal)); } @Override - public <MergedType> MergedType merge(final BiFunction<LeftType, RightType, MergedType> merger) { - if(merger == null) throw new NullPointerException("Merger must not be null"); + public <MergedType> MergedType + merge(final BiFunction<LeftType, RightType, MergedType> merger) { + if (merger == null) + throw new NullPointerException("Merger must not be null"); return merger.apply(leftVal, rightVal); } @@ -165,27 +182,36 @@ public class Either<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof Either<?, ?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Either<?, ?>)) + return false; final Either<?, ?> other = (Either<?, ?>) obj; - if(isLeft != other.isLeft) return false; + if (isLeft != other.isLeft) + return false; - if(leftVal == null) { - if(other.leftVal != null) return false; - } else if(!leftVal.equals(other.leftVal)) return false; + if (leftVal == null) { + if (other.leftVal != null) + return false; + } else if (!leftVal.equals(other.leftVal)) + return false; - if(rightVal == null) { - if(other.rightVal != null) return false; - } else if(!rightVal.equals(other.rightVal)) return false; + if (rightVal == null) { + if (other.rightVal != null) + return false; + } else if (!rightVal.equals(other.rightVal)) + return false; return true; } @Override public String toString() { - return String.format("Either [leftVal='%s', rightVal='%s', isLeft=%s]", leftVal, rightVal, isLeft); + return String.format("Either [leftVal='%s', rightVal='%s', isLeft=%s]", leftVal, + rightVal, isLeft); } } diff --git a/src/main/java/bjc/data/GeneratingIterator.java b/src/main/java/bjc/data/GeneratingIterator.java index 9adda6f..ffa92cf 100644 --- a/src/main/java/bjc/data/GeneratingIterator.java +++ b/src/main/java/bjc/data/GeneratingIterator.java @@ -6,11 +6,11 @@ import java.util.function.UnaryOperator; /** * An iterator that generates a series of elements from a single element. - * + * * @author bjculkin * * @param <E> - * The type of element generated. + * The type of element generated. */ public class GeneratingIterator<E> implements Iterator<E> { /* Our current state. */ @@ -22,18 +22,19 @@ public class GeneratingIterator<E> implements Iterator<E> { /** * Create a new generative iterator. - * + * * @param initial - * The initial state of the generator. - * + * The initial state of the generator. + * * @param transition - * The function to apply to the state. - * + * The function to apply to the state. + * * @param stopper - * The predicate applied to the current state to determine when - * to stop. + * The predicate applied to the current state to determine + * when to stop. */ - public GeneratingIterator(E initial, UnaryOperator<E> transition, Predicate<E> stopper) { + public GeneratingIterator(E initial, UnaryOperator<E> transition, + Predicate<E> stopper) { state = initial; transtion = transition; stpper = stopper; @@ -47,9 +48,9 @@ public class GeneratingIterator<E> implements Iterator<E> { /* * @NOTE * - * As this currently is, it only works correctly assuming that next() is - * only called when hasNext() is true. Should we safeguard against - * people who are not doing the right thing? + * As this currently is, it only works correctly assuming that next() is only + * called when hasNext() is true. Should we safeguard against people who are not + * doing the right thing? */ @Override public E next() { diff --git a/src/main/java/bjc/data/IHolder.java b/src/main/java/bjc/data/IHolder.java index e56e23e..faa3f64 100644 --- a/src/main/java/bjc/data/IHolder.java +++ b/src/main/java/bjc/data/IHolder.java @@ -16,27 +16,28 @@ import bjc.funcdata.theory.Functor; * @author ben * * @param <ContainedType> - * The type of value held. + * The type of value held. */ public interface IHolder<ContainedType> extends Functor<ContainedType> { /** * Bind a function across the value in this container. * * @param <BoundType> - * The type of value in this container. + * The type of value in this container. * * @param binder - * The function to bind to the value. + * The function to bind to the value. * * @return A holder from binding the value. */ - public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder); + public <BoundType> IHolder<BoundType> + bind(Function<ContainedType, IHolder<BoundType>> binder); /** * Apply an action to the value. * * @param action - * The action to apply to the value. + * The action to apply to the value. */ public default void doWith(final Consumer<? super ContainedType> action) { transform(value -> { @@ -47,11 +48,12 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { } @Override - default <ArgType, ReturnType> Function<Functor<ArgType>, Functor<ReturnType>> fmap( - final Function<ArgType, ReturnType> func) { + default <ArgType, ReturnType> Function<Functor<ArgType>, Functor<ReturnType>> + fmap(final Function<ArgType, ReturnType> func) { return argumentFunctor -> { - if(!(argumentFunctor instanceof IHolder<?>)) { - final String msg = "This functor only supports mapping over instances of IHolder"; + if (!(argumentFunctor instanceof IHolder<?>)) { + final String msg + = "This functor only supports mapping over instances of IHolder"; throw new IllegalArgumentException(msg); } @@ -71,14 +73,15 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { * Lifts a function to bind over this holder. * * @param <NewType> - * The type of the functions return. + * The type of the functions return. * * @param func - * The function to lift over the holder. + * The function to lift over the holder. * * @return The function lifted over the holder. */ - public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func); + public <NewType> Function<ContainedType, IHolder<NewType>> + lift(Function<ContainedType, NewType> func); /** * Make this holder lazy. @@ -108,56 +111,54 @@ public interface IHolder<ContainedType> extends Functor<ContainedType> { } /** - * Create a new holder with a mapped version of the value in this - * holder. + * Create a new holder with a mapped version of the value in this holder. * * Does not change the internal state of this holder. * * @param <MappedType> - * The type of the mapped value. + * The type of the mapped value. * * @param mapper - * The function to do mapping with. + * The function to do mapping with. * * @return A holder with the mapped value */ - public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper); + public <MappedType> IHolder<MappedType> + map(Function<ContainedType, MappedType> mapper); /** * Replace the held value with a new one. * * @param newValue - * The value to hold instead. + * The value to hold instead. * * @return The holder itself. */ public default IHolder<ContainedType> replace(final ContainedType newValue) { - return transform(oldValue -> { - return newValue; - }); + return transform(oldValue -> newValue); } /** * Transform the value held in this holder. * * @param transformer - * The function to transform the value with. + * The function to transform the value with. * * @return The holder itself, for easy chaining. */ public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer); /** - * Unwrap the value contained in this holder so that it is no longer - * held. + * Unwrap the value contained in this holder so that it is no longer held. * * @param <UnwrappedType> - * The type of the unwrapped value. + * The type of the unwrapped value. * * @param unwrapper - * The function to use to unwrap the value. + * The function to use to unwrap the value. * * @return The unwrapped held value. */ - public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper); + public <UnwrappedType> UnwrappedType + unwrap(Function<ContainedType, UnwrappedType> unwrapper); } diff --git a/src/main/java/bjc/data/IPair.java b/src/main/java/bjc/data/IPair.java index 0c63f16..5b1298e 100644 --- a/src/main/java/bjc/data/IPair.java +++ b/src/main/java/bjc/data/IPair.java @@ -12,10 +12,10 @@ import bjc.funcdata.theory.Bifunctor; * @author ben * * @param <LeftType> - * The type of the left side of the pair. + * The type of the left side of the pair. * * @param <RightType> - * The type of the right side of the pair. + * The type of the right side of the pair. * */ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightType> { @@ -23,103 +23,105 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Bind a function across the values in this pair. * * @param <BoundLeft> - * The type of the bound left. + * The type of the bound left. * * @param <BoundRight> - * The type of the bound right. + * The type of the bound right. * * @param binder - * The function to bind with. + * The function to bind with. * * @return The bound pair. */ - public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( - BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder); + public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> + bind(BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder); /** * Bind a function to the left value in this pair. * * @param <BoundLeft> - * The type of the bound value. + * The type of the bound value. * * @param leftBinder - * The function to use to bind. + * The function to use to bind. * * @return A pair with the left type bound. */ - public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( - Function<LeftType, IPair<BoundLeft, RightType>> leftBinder); + public <BoundLeft> IPair<BoundLeft, RightType> + bindLeft(Function<LeftType, IPair<BoundLeft, RightType>> leftBinder); /** * Bind a function to the right value in this pair. * * @param <BoundRight> - * The type of the bound value. + * The type of the bound value. * * @param rightBinder - * The function to use to bind. + * The function to use to bind. * * @return A pair with the right type bound. */ - public <BoundRight> IPair<LeftType, BoundRight> bindRight( - Function<RightType, IPair<LeftType, BoundRight>> rightBinder); + public <BoundRight> IPair<LeftType, BoundRight> + bindRight(Function<RightType, IPair<LeftType, BoundRight>> rightBinder); /** * Pairwise combine two pairs together. * * @param <OtherLeft> - * The left type of the other pair. + * The left type of the other pair. * * @param <OtherRight> - * The right type of the other pair. + * The right type of the other pair. * * @param otherPair - * The pair to combine with. + * The pair to combine with. * * @return The pairs, pairwise combined together. */ - public default <OtherLeft, OtherRight> IPair<IPair<LeftType, OtherLeft>, IPair<RightType, OtherRight>> combine( - final IPair<OtherLeft, OtherRight> otherPair) { - return combine(otherPair, Pair<LeftType, OtherLeft>::new, Pair<RightType, OtherRight>::new); + public default <OtherLeft, OtherRight> + IPair<IPair<LeftType, OtherLeft>, IPair<RightType, OtherRight>> + combine(final IPair<OtherLeft, OtherRight> otherPair) { + return combine(otherPair, Pair<LeftType, OtherLeft>::new, + Pair<RightType, OtherRight>::new); } /** * Combine the contents of two pairs together. * * @param <OtherLeft> - * The type of the left value of the other pair. + * The type of the left value of the other pair. * * @param <OtherRight> - * The type of the right value of the other pair. + * The type of the right value of the other pair. * * @param <CombinedLeft> - * The type of the left value of the combined pair. + * The type of the left value of the combined pair. * * @param <CombinedRight> - * The type of the right value of the combined pair. + * The type of the right value of the combined pair. * * @param otherPair - * The other pair to combine with. + * The other pair to combine with. * * @param leftCombiner - * The function to combine the left values with. + * The function to combine the left values with. * * @param rightCombiner - * The function to combine the right values with. + * The function to combine the right values with. * * @return A pair with its values combined. */ - public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - IPair<OtherLeft, OtherRight> otherPair, - BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, - BiFunction<RightType, OtherRight, CombinedRight> rightCombiner); + public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> + IPair<CombinedLeft, CombinedRight> + combine(IPair<OtherLeft, OtherRight> otherPair, + BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + BiFunction<RightType, OtherRight, CombinedRight> rightCombiner); /** - * Immediately perfom the specified action with the contents of this - * pair. + * Immediately perfom the specified action with the contents of this pair. * * @param consumer - * The action to perform on the pair. + * The action to perform on the pair. */ public default void doWith(final BiConsumer<LeftType, RightType> consumer) { merge((leftValue, rightValue) -> { @@ -130,32 +132,36 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp } @Override - default <OldLeft, OldRight, NewLeft> LeftBifunctorMap<OldLeft, OldRight, NewLeft> fmapLeft( - final Function<OldLeft, NewLeft> func) { + default <OldLeft, OldRight, NewLeft> LeftBifunctorMap<OldLeft, OldRight, NewLeft> + fmapLeft(final Function<OldLeft, NewLeft> func) { return argumentPair -> { if (!(argumentPair instanceof IPair<?, ?>)) { - final String msg = "This function can only be applied to instances of IPair"; + final String msg + = "This function can only be applied to instances of IPair"; throw new IllegalArgumentException(msg); } - final IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, OldRight>) argumentPair; + final IPair<OldLeft, OldRight> argPair + = (IPair<OldLeft, OldRight>) argumentPair; return argPair.mapLeft(func); }; } @Override - default <OldLeft, OldRight, NewRight> RightBifunctorMap<OldLeft, OldRight, NewRight> fmapRight( - final Function<OldRight, NewRight> func) { + default <OldLeft, OldRight, NewRight> RightBifunctorMap<OldLeft, OldRight, NewRight> + fmapRight(final Function<OldRight, NewRight> func) { return argumentPair -> { if (!(argumentPair instanceof IPair<?, ?>)) { - final String msg = "This function can only be applied to instances of IPair"; + final String msg + = "This function can only be applied to instances of IPair"; throw new IllegalArgumentException(msg); } - final IPair<OldLeft, OldRight> argPair = (IPair<OldLeft, OldRight>) argumentPair; + final IPair<OldLeft, OldRight> argPair + = (IPair<OldLeft, OldRight>) argumentPair; return argPair.mapRight(func); }; @@ -187,15 +193,15 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Doesn't modify the pair. * * @param <NewLeft> - * The new type of the left part of the pair. + * The new type of the left part of the pair. * * @param mapper - * The function to use to transform the left part of the - * pair. + * The function to use to transform the left part of the pair. * * @return The pair, with its left part transformed. */ - public <NewLeft> IPair<NewLeft, RightType> mapLeft(Function<LeftType, NewLeft> mapper); + public <NewLeft> IPair<NewLeft, RightType> + mapLeft(Function<LeftType, NewLeft> mapper); /** * Transform the value on the right side of the pair. @@ -203,36 +209,38 @@ public interface IPair<LeftType, RightType> extends Bifunctor<LeftType, RightTyp * Doesn't modify the pair. * * @param <NewRight> - * The new type of the right part of the pair. + * The new type of the right part of the pair. * * @param mapper - * The function to use to transform the right part of the - * pair. + * The function to use to transform the right part of the + * pair. * * @return The pair, with its right part transformed. */ - public <NewRight> IPair<LeftType, NewRight> mapRight(Function<RightType, NewRight> mapper); + public <NewRight> IPair<LeftType, NewRight> + mapRight(Function<RightType, NewRight> mapper); /** * Merge the two values in this pair into a single value. * * @param <MergedType> - * The type of the single value. + * The type of the single value. * * @param merger - * The function to use for merging. + * The function to use for merging. * * @return The pair, merged into a single value. */ - public <MergedType> MergedType merge(BiFunction<LeftType, RightType, MergedType> merger); + public <MergedType> MergedType + merge(BiFunction<LeftType, RightType, MergedType> merger); /** * Static pair constructor. - * + * * @param left - * The left side of the pair. + * The left side of the pair. * @param right - * The right side of the pair. + * The right side of the pair. * @return A pair, with the specified left/right side. */ public static <T1, T2> IPair<T1, T2> pair(T1 left, T2 right) { diff --git a/src/main/java/bjc/data/ITree.java b/src/main/java/bjc/data/ITree.java index 4088c10..e9c829e 100644 --- a/src/main/java/bjc/data/ITree.java +++ b/src/main/java/bjc/data/ITree.java @@ -15,7 +15,7 @@ import bjc.funcdata.bst.TreeLinearizationMethod; * @author ben * * @param <ContainedType> - * The type of data contained in the tree nodes. + * The type of data contained in the tree nodes. * */ public interface ITree<ContainedType> { @@ -23,7 +23,7 @@ public interface ITree<ContainedType> { * Append a child to this node. * * @param child - * The child to append to this node. + * The child to append to this node. */ void addChild(ITree<ContainedType> child); @@ -31,7 +31,7 @@ public interface ITree<ContainedType> { * Append a child to this node. * * @param child - * The child to append to this node. + * The child to append to this node. */ void addChild(ContainedType child); @@ -39,7 +39,7 @@ public interface ITree<ContainedType> { * Prepend a child to this node. * * @param child - * The child to prepend to this node. + * The child to prepend to this node. */ void prependChild(ITree<ContainedType> child); @@ -47,25 +47,26 @@ public interface ITree<ContainedType> { * Collapse a tree into a single version. * * @param <NewType> - * The intermediate type being folded. + * The intermediate type being folded. * * @param <ReturnedType> - * The type that is the end result. + * The type that is the end result. * * @param leafTransform - * The function to use to convert leaf values. + * The function to use to convert leaf values. * * @param nodeCollapser - * The function to use to convert internal nodes and their - * children. + * The function to use to convert internal nodes and + * their children. * * @param resultTransformer - * The function to use to convert a state to the returned - * version. + * The function to use to convert a state to the + * returned version. * * @return The final transformed state. */ - <NewType, ReturnedType> ReturnedType collapse(Function<ContainedType, NewType> leafTransform, + <NewType, ReturnedType> ReturnedType collapse( + Function<ContainedType, NewType> leafTransform, BiFunction<ContainedType, IList<NewType>, NewType> nodeCollapser, Function<NewType, ReturnedType> resultTransformer); @@ -73,22 +74,23 @@ public interface ITree<ContainedType> { * Execute a given action for each of this tree's children. * * @param action - * The action to execute for each child. + * The action to execute for each child. */ void doForChildren(Consumer<ITree<ContainedType>> action); /** - * Expand the nodes of a tree into trees, and then merge the contents of - * those trees into a single tree. + * Expand the nodes of a tree into trees, and then merge the contents of those + * trees into a single tree. * * @param mapper - * The function to use to map values into trees. + * The function to use to map values into trees. * * @return A tree, with some nodes expanded into trees. */ - default ITree<ContainedType> flatMapTree(final Function<ContainedType, ITree<ContainedType>> mapper) { + default ITree<ContainedType> + flatMapTree(final Function<ContainedType, ITree<ContainedType>> mapper) { return topDownTransform(dat -> TopDownTransformResult.PUSHDOWN, node -> { - if(node.getChildrenCount() > 0) { + if (node.getChildrenCount() > 0) { final ITree<ContainedType> parent = node.transformHead(mapper); node.doForChildren(parent::addChild); @@ -104,7 +106,7 @@ public interface ITree<ContainedType> { * Get the specified child of this tree. * * @param childNo - * The number of the child to get. + * The number of the child to get. * * @return The specified child of this tree. */ @@ -141,61 +143,64 @@ public interface ITree<ContainedType> { * Rebuild the tree with the same structure, but different nodes. * * @param <MappedType> - * The type of the new tree. + * The type of the new tree. * * @param leafTransformer - * The function to use to transform leaf tokens. + * The function to use to transform leaf tokens. * * @param internalTransformer - * The function to use to transform internal tokens. + * The function to use to transform internal tokens. * * @return The tree, with the nodes changed. */ - <MappedType> ITree<MappedType> rebuildTree(Function<ContainedType, MappedType> leafTransformer, + <MappedType> ITree<MappedType> rebuildTree( + Function<ContainedType, MappedType> leafTransformer, Function<ContainedType, MappedType> internalTransformer); /** * Transform some of the nodes in this tree. * * @param nodePicker - * The predicate to use to pick nodes to transform. + * The predicate to use to pick nodes to transform. * * @param transformer - * The function to use to transform picked nodes. + * The function to use to transform picked nodes. */ - void selectiveTransform(Predicate<ContainedType> nodePicker, UnaryOperator<ContainedType> transformer); + void selectiveTransform(Predicate<ContainedType> nodePicker, + UnaryOperator<ContainedType> transformer); /** * Do a top-down transform of the tree. * * @param transformPicker - * The function to use to pick how to progress. + * The function to use to pick how to progress. * * @param transformer - * The function used to transform picked subtrees. + * The function used to transform picked subtrees. * * @return The tree with the transform applied to picked subtrees. */ - ITree<ContainedType> topDownTransform(Function<ContainedType, TopDownTransformResult> transformPicker, + ITree<ContainedType> topDownTransform( + Function<ContainedType, TopDownTransformResult> transformPicker, UnaryOperator<ITree<ContainedType>> transformer); /** * Transform one of this nodes children. * * @param <TransformedType> - * The type of the transformed value. + * The type of the transformed value. * * @param childNo - * The number of the child to transform. + * The number of the child to transform. * * @param transformer - * The function to use to transform the value. + * The function to use to transform the value. * * @return The transformed value. * * @throws IllegalArgumentException - * if the childNo is out of bounds (0 <= childNo <= - * childCount()). + * if the childNo is out of bounds (0 <= + * childNo <= childCount()). */ <TransformedType> TransformedType transformChild(int childNo, Function<ITree<ContainedType>, TransformedType> transformer); @@ -204,27 +209,29 @@ public interface ITree<ContainedType> { * Transform the value that is the head of this node. * * @param <TransformedType> - * The type of the transformed value. + * The type of the transformed value. * * @param transformer - * The function to use to transform the value. + * The function to use to transform the value. * * @return The transformed value. */ - <TransformedType> TransformedType transformHead(Function<ContainedType, TransformedType> transformer); + <TransformedType> TransformedType + transformHead(Function<ContainedType, TransformedType> transformer); /** * Transform the tree into a tree with a different type of token. * * @param <MappedType> - * The type of the new tree. + * The type of the new tree. * * @param transformer - * The function to use to transform tokens. + * The function to use to transform tokens. * * @return A tree with the token types transformed. */ - default <MappedType> ITree<MappedType> transformTree(final Function<ContainedType, MappedType> transformer) { + default <MappedType> ITree<MappedType> + transformTree(final Function<ContainedType, MappedType> transformer) { return rebuildTree(transformer, transformer); } @@ -232,21 +239,22 @@ public interface ITree<ContainedType> { * Perform an action on each part of the tree. * * @param linearizationMethod - * The way to traverse the tree. + * The way to traverse the tree. * * @param action - * The action to perform on each tree node. + * The action to perform on each tree node. */ - void traverse(TreeLinearizationMethod linearizationMethod, Consumer<ContainedType> action); + void traverse(TreeLinearizationMethod linearizationMethod, + Consumer<ContainedType> action); /** * Find the farthest to right child that satisfies the given predicate. * * @param childPred - * The predicate to satisfy. + * The predicate to satisfy. * - * @return The index of the right-most child that satisfies the - * predicate, or -1 if one doesn't exist. + * @return The index of the right-most child that satisfies the predicate, or -1 + * if one doesn't exist. */ int revFind(Predicate<ITree<ContainedType>> childPred); @@ -254,15 +262,16 @@ public interface ITree<ContainedType> { * Check if this tree contains any nodes that satisfy the predicate. * * @param pred - * The predicate to look for. - * + * The predicate to look for. + * * @return Whether or not any items satisfied the predicate. */ default boolean containsMatching(Predicate<ContainedType> pred) { Toggle<Boolean> tog = new OneWayToggle<>(false, true); - traverse(TreeLinearizationMethod.POSTORDER, (val) -> { - if(pred.test(val)) tog.get(); + traverse(TreeLinearizationMethod.POSTORDER, val -> { + if (pred.test(val)) + tog.get(); }); return tog.get(); @@ -272,7 +281,7 @@ public interface ITree<ContainedType> { * Set the head of the tree. * * @param dat - * The value to set as the head of the tree. + * The value to set as the head of the tree. */ void setHead(ContainedType dat); } diff --git a/src/main/java/bjc/data/Identity.java b/src/main/java/bjc/data/Identity.java index 8645c4c..c80c7e1 100644 --- a/src/main/java/bjc/data/Identity.java +++ b/src/main/java/bjc/data/Identity.java @@ -9,7 +9,7 @@ import java.util.function.UnaryOperator; * @author ben * * @param <ContainedType> - * The type contained in the holder. + * The type contained in the holder. */ public class Identity<ContainedType> implements IHolder<ContainedType> { /* The held value. */ @@ -24,14 +24,15 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { * Create a holder holding the specified value. * * @param value - * The value to hold. + * The value to hold. */ public Identity(final ContainedType value) { heldValue = value; } @Override - public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { + public <BoundType> IHolder<BoundType> + bind(final Function<ContainedType, IHolder<BoundType>> binder) { return binder.apply(heldValue); } @@ -47,28 +48,35 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof Identity)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Identity)) + return false; final Identity<?> other = (Identity<?>) obj; - if(heldValue == null) { - if(other.heldValue != null) return false; - } else if(!heldValue.equals(other.heldValue)) return false; + if (heldValue == null) { + if (other.heldValue != null) + return false; + } else if (!heldValue.equals(other.heldValue)) + return false; return true; } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { - return (val) -> { + public <NewType> Function<ContainedType, IHolder<NewType>> + lift(final Function<ContainedType, NewType> func) { + return val -> { return new Identity<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> + map(final Function<ContainedType, MappedType> mapper) { return new Identity<>(mapper.apply(heldValue)); } @@ -78,14 +86,16 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> + transform(final UnaryOperator<ContainedType> transformer) { heldValue = transformer.apply(heldValue); return this; } @Override - public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType + unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { return unwrapper.apply(heldValue); } @@ -93,7 +103,7 @@ public class Identity<ContainedType> implements IHolder<ContainedType> { * Create a new identity container. * * @param val - * The contained value. + * The contained value. * * @return A new identity container. */ diff --git a/src/main/java/bjc/data/Lazy.java b/src/main/java/bjc/data/Lazy.java index 0702665..a425232 100644 --- a/src/main/java/bjc/data/Lazy.java +++ b/src/main/java/bjc/data/Lazy.java @@ -15,7 +15,7 @@ import bjc.funcdata.IList; * @author ben * * @param <ContainedType> - * The type of the value being held. + * The type of the value being held. */ public class Lazy<ContainedType> implements IHolder<ContainedType> { /* The supplier of the type. */ @@ -32,7 +32,7 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { * Create a new lazy value from the specified seed value. * * @param value - * The seed value to use. + * The seed value to use. */ public Lazy(final ContainedType value) { heldValue = value; @@ -44,7 +44,7 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { * Create a new lazy value from the specified value source. * * @param supp - * The source of a value to use. + * The source of a value to use. */ public Lazy(final Supplier<ContainedType> supp) { valueSupplier = new SingleSupplier<>(supp); @@ -53,38 +53,39 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { } /* Create a new value from a supplier and a list of actions. */ - private Lazy(final Supplier<ContainedType> supp, final IList<UnaryOperator<ContainedType>> pendingActions) { + private Lazy(final Supplier<ContainedType> supp, + final IList<UnaryOperator<ContainedType>> pendingActions) { valueSupplier = supp; actions = pendingActions; } @Override - public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { + public <BoundType> IHolder<BoundType> + bind(final Function<ContainedType, IHolder<BoundType>> binder) { final IList<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); final Supplier<ContainedType> supplier = () -> { - if(valueMaterialized) return heldValue; + if (valueMaterialized) + return heldValue; return valueSupplier.get(); }; - return new BoundLazy<>(() -> { - return new Lazy<>(supplier, pendingActions); - }, binder); + return new BoundLazy<>(() -> new Lazy<>(supplier, pendingActions), binder); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { - return val -> { - return new Lazy<>(func.apply(val)); - }; + public <NewType> Function<ContainedType, IHolder<NewType>> + lift(final Function<ContainedType, NewType> func) { + return val -> new Lazy<>(func.apply(val)); } @Override - public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> + map(final Function<ContainedType, MappedType> mapper) { final IList<UnaryOperator<ContainedType>> pendingActions = new FunctionalList<>(); actions.forEach(pendingActions::add); @@ -92,7 +93,7 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { return new Lazy<>(() -> { ContainedType currVal = heldValue; - if(!valueMaterialized) { + if (!valueMaterialized) { currVal = valueSupplier.get(); } @@ -103,8 +104,8 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { @Override public String toString() { - if(valueMaterialized) { - if(actions.isEmpty()) { + if (valueMaterialized) { + if (actions.isEmpty()) { return String.format("value[v='%s']", heldValue); } @@ -115,15 +116,17 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> + transform(final UnaryOperator<ContainedType> transformer) { actions.add(transformer); return this; } @Override - public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { - if(!valueMaterialized) { + public <UnwrappedType> UnwrappedType + unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { + if (!valueMaterialized) { heldValue = valueSupplier.get(); valueMaterialized = true; @@ -152,24 +155,32 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof Lazy<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Lazy<?>)) + return false; final Lazy<?> other = (Lazy<?>) obj; - if(valueMaterialized != other.valueMaterialized) return false; + if (valueMaterialized != other.valueMaterialized) + return false; - if(valueMaterialized) { - if(heldValue == null) { - if(other.heldValue != null) return false; - } else if(!heldValue.equals(other.heldValue)) return false; + if (valueMaterialized) { + if (heldValue == null) { + if (other.heldValue != null) + return false; + } else if (!heldValue.equals(other.heldValue)) + return false; } else return false; - if(actions == null) { - if(other.actions != null) return false; - } else if(actions.getSize() > 0 || other.actions.getSize() > 0) return false; + if (actions == null) { + if (other.actions != null) + return false; + } else if (actions.getSize() > 0 || other.actions.getSize() > 0) + return false; return true; } @@ -178,7 +189,7 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { * Create a new lazy container with an already present value. * * @param val - * The value for the lazy container. + * The value for the lazy container. * * @return A new lazy container holding that value. */ @@ -190,12 +201,12 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> { * Create a new lazy container with a suspended value. * * @param supp - * The suspended value for the lazy container. + * The suspended value for the lazy container. * - * @return A new lazy container that will un-suspend the value when - * necessary. + * @return A new lazy container that will un-suspend the value when necessary. */ - public static <ContainedType> Lazy<ContainedType> lazy(final Supplier<ContainedType> supp) { + public static <ContainedType> Lazy<ContainedType> + lazy(final Supplier<ContainedType> supp) { return new Lazy<>(supp); } } diff --git a/src/main/java/bjc/data/LazyPair.java b/src/main/java/bjc/data/LazyPair.java index 1633c65..e668cd4 100644 --- a/src/main/java/bjc/data/LazyPair.java +++ b/src/main/java/bjc/data/LazyPair.java @@ -13,10 +13,10 @@ import bjc.data.internals.HalfBoundLazyPair; * @author ben * * @param <LeftType> - * The type on the left side of the pair. + * The type on the left side of the pair. * * @param <RightType> - * The type on the right side of the pair. + * The type on the right side of the pair. */ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> { /* The supplier for the left value. */ @@ -37,10 +37,10 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> * Create a new lazy pair, using the set values. * * @param leftVal - * The value for the left side of the pair. + * The value for the left side of the pair. * * @param rightVal - * The value for the right side of the pair. + * The value for the right side of the pair. */ public LazyPair(final LeftType leftVal, final RightType rightVal) { leftValue = leftVal; @@ -54,12 +54,13 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> * Create a new lazy pair from the given value sources. * * @param leftSupp - * The source for a value on the left side of the pair. + * The source for a value on the left side of the pair. * * @param rightSupp - * The source for a value on the right side of the pair. + * The source for a value on the right side of the pair. */ - public LazyPair(final Supplier<LeftType> leftSupp, final Supplier<RightType> rightSupp) { + public LazyPair(final Supplier<LeftType> leftSupp, + final Supplier<RightType> rightSupp) { /* Use single suppliers to catch double-instantiation bugs. */ leftSupplier = new SingleSupplier<>(leftSupp); rightSupplier = new SingleSupplier<>(rightSupp); @@ -75,10 +76,11 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> } @Override - public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( - final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + public <BoundLeft> IPair<BoundLeft, RightType> + bindLeft(final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { final Supplier<LeftType> leftSupp = () -> { - if(leftMaterialized) return leftValue; + if (leftMaterialized) + return leftValue; return leftSupplier.get(); }; @@ -90,7 +92,8 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> public <BoundRight> IPair<LeftType, BoundRight> bindRight( final Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { final Supplier<RightType> rightSupp = () -> { - if(rightMaterialized) return rightValue; + if (rightMaterialized) + return rightValue; return rightSupplier.get(); }; @@ -99,23 +102,23 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> } @Override - public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - final IPair<OtherLeft, OtherRight> otherPair, - final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, - final BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { - return otherPair.bind((otherLeft, otherRight) -> { - return bind((leftVal, rightVal) -> { - final CombinedLeft left = leftCombiner.apply(leftVal, otherLeft); - final CombinedRight right = rightCombiner.apply(rightVal, otherRight); - - return new LazyPair<>(left, right); - }); - }); + public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> + IPair<CombinedLeft, CombinedRight> + combine(final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<RightType, OtherRight, + CombinedRight> rightCombiner) { + return otherPair.bind((otherLeft, otherRight) -> bind((leftVal, rightVal) -> { + final CombinedLeft left = leftCombiner.apply(leftVal, otherLeft); + final CombinedRight right = rightCombiner.apply(rightVal, otherRight); + + return new LazyPair<>(left, right); + })); } @Override public LeftType getLeft() { - if(!leftMaterialized) { + if (!leftMaterialized) { leftValue = leftSupplier.get(); leftMaterialized = true; @@ -126,7 +129,7 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public RightType getRight() { - if(!rightMaterialized) { + if (!rightMaterialized) { rightValue = rightSupplier.get(); rightMaterialized = true; @@ -136,15 +139,18 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> } @Override - public <NewLeft> IPair<NewLeft, RightType> mapLeft(final Function<LeftType, NewLeft> mapper) { + public <NewLeft> IPair<NewLeft, RightType> + mapLeft(final Function<LeftType, NewLeft> mapper) { final Supplier<NewLeft> leftSupp = () -> { - if(leftMaterialized) return mapper.apply(leftValue); + if (leftMaterialized) + return mapper.apply(leftValue); return mapper.apply(leftSupplier.get()); }; final Supplier<RightType> rightSupp = () -> { - if(rightMaterialized) return rightValue; + if (rightMaterialized) + return rightValue; return rightSupplier.get(); }; @@ -153,15 +159,18 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> } @Override - public <NewRight> IPair<LeftType, NewRight> mapRight(final Function<RightType, NewRight> mapper) { + public <NewRight> IPair<LeftType, NewRight> + mapRight(final Function<RightType, NewRight> mapper) { final Supplier<LeftType> leftSupp = () -> { - if(leftMaterialized) return leftValue; + if (leftMaterialized) + return leftValue; return leftSupplier.get(); }; final Supplier<NewRight> rightSupp = () -> { - if(rightMaterialized) return mapper.apply(rightValue); + if (rightMaterialized) + return mapper.apply(rightValue); return mapper.apply(rightSupplier.get()); }; @@ -170,14 +179,15 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> } @Override - public <MergedType> MergedType merge(final BiFunction<LeftType, RightType, MergedType> merger) { - if(!leftMaterialized) { + public <MergedType> MergedType + merge(final BiFunction<LeftType, RightType, MergedType> merger) { + if (!leftMaterialized) { leftValue = leftSupplier.get(); leftMaterialized = true; } - if(!rightMaterialized) { + if (!rightMaterialized) { rightValue = rightSupplier.get(); rightMaterialized = true; @@ -191,13 +201,13 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> String leftVal; String rightVal; - if(leftMaterialized) { + if (leftMaterialized) { leftVal = leftValue.toString(); } else { leftVal = "(un-materialized)"; } - if(rightMaterialized) { + if (rightMaterialized) { rightVal = rightValue.toString(); } else { rightVal = "(un-materialized)"; @@ -221,26 +231,35 @@ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof LazyPair<?, ?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof LazyPair<?, ?>)) + return false; final LazyPair<?, ?> other = (LazyPair<?, ?>) obj; - if(leftMaterialized != other.leftMaterialized) return false; + if (leftMaterialized != other.leftMaterialized) + return false; - if(leftMaterialized) { - if(leftValue == null) { - if(other.leftValue != null) return false; - } else if(!leftValue.equals(other.leftValue)) return false; + if (leftMaterialized) { + if (leftValue == null) { + if (other.leftValue != null) + return false; + } else if (!leftValue.equals(other.leftValue)) + return false; } else return false; - if(rightMaterialized != other.rightMaterialized) return false; - if(rightMaterialized) { - if(rightValue == null) { - if(other.rightValue != null) return false; - } else if(!rightValue.equals(other.rightValue)) return false; + if (rightMaterialized != other.rightMaterialized) + return false; + if (rightMaterialized) { + if (rightValue == null) { + if (other.rightValue != null) + return false; + } else if (!rightValue.equals(other.rightValue)) + return false; } else return false; diff --git a/src/main/java/bjc/data/ListHolder.java b/src/main/java/bjc/data/ListHolder.java index 077c0fb..ab3bfa8 100644 --- a/src/main/java/bjc/data/ListHolder.java +++ b/src/main/java/bjc/data/ListHolder.java @@ -13,7 +13,7 @@ import bjc.funcdata.IList; * @author ben * * @param <ContainedType> - * The type of contained value. + * The type of contained value. */ public class ListHolder<ContainedType> implements IHolder<ContainedType> { private IList<ContainedType> heldValues; @@ -22,14 +22,14 @@ public class ListHolder<ContainedType> implements IHolder<ContainedType> { * Create a new list holder. * * @param values - * The possible values for the computation. + * The possible values for the computation. */ @SafeVarargs public ListHolder(final ContainedType... values) { heldValues = new FunctionalList<>(); - if(values != null) { - for(final ContainedType containedValue : values) { + if (values != null) { + for (final ContainedType containedValue : values) { heldValues.add(containedValue); } } @@ -41,35 +41,38 @@ public class ListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { + public <BoundType> IHolder<BoundType> + bind(final Function<ContainedType, IHolder<BoundType>> binder) { final IList<IHolder<BoundType>> boundValues = heldValues.map(binder); return new BoundListHolder<>(boundValues); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { - return val -> { - return new ListHolder<>(new FunctionalList<>(func.apply(val))); - }; + public <NewType> Function<ContainedType, IHolder<NewType>> + lift(final Function<ContainedType, NewType> func) { + return val -> new ListHolder<>(new FunctionalList<>(func.apply(val))); } @Override - public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> + map(final Function<ContainedType, MappedType> mapper) { final IList<MappedType> mappedValues = heldValues.map(mapper); return new ListHolder<>(mappedValues); } @Override - public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> + transform(final UnaryOperator<ContainedType> transformer) { heldValues = heldValues.map(transformer); return this; } @Override - public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType + unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { return unwrapper.apply(heldValues.randItem()); } @@ -90,15 +93,20 @@ public class ListHolder<ContainedType> implements IHolder<ContainedType> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof ListHolder<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof ListHolder<?>)) + return false; final ListHolder<?> other = (ListHolder<?>) obj; - if(heldValues == null) { - if(other.heldValues != null) return false; - } else if(!heldValues.equals(other.heldValues)) return false; + if (heldValues == null) { + if (other.heldValues != null) + return false; + } else if (!heldValues.equals(other.heldValues)) + return false; return true; } diff --git a/src/main/java/bjc/data/OneWayToggle.java b/src/main/java/bjc/data/OneWayToggle.java index a4557cd..c2e9e4b 100644 --- a/src/main/java/bjc/data/OneWayToggle.java +++ b/src/main/java/bjc/data/OneWayToggle.java @@ -3,7 +3,7 @@ package bjc.data; /** * A toggle that will only give the first value once, only yielding the second * value afterwards. - * + * * @author student * * @param <E> @@ -17,11 +17,11 @@ public class OneWayToggle<E> implements Toggle<E> { /** * Create a new one-way toggle - * + * * @param first - * The value to offer first, and only once + * The value to offer first, and only once * @param second - * The value to offer second and repeatedly + * The value to offer second and repeatedly */ public OneWayToggle(E first, E second) { this.first = first; diff --git a/src/main/java/bjc/data/Option.java b/src/main/java/bjc/data/Option.java index a180ef9..b5d6d5e 100644 --- a/src/main/java/bjc/data/Option.java +++ b/src/main/java/bjc/data/Option.java @@ -9,7 +9,7 @@ import java.util.function.UnaryOperator; * @author ben * * @param <ContainedType> - * The type of the value that may or may not be held. + * The type of the value that may or may not be held. */ public class Option<ContainedType> implements IHolder<ContainedType> { private ContainedType held; @@ -18,36 +18,40 @@ public class Option<ContainedType> implements IHolder<ContainedType> { * Create a new optional, using the given initial value. * * @param seed - * The initial value for the optional. + * The initial value for the optional. */ public Option(final ContainedType seed) { held = seed; } @Override - public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { - if(held == null) return new Option<>(null); + public <BoundType> IHolder<BoundType> + bind(final Function<ContainedType, IHolder<BoundType>> binder) { + if (held == null) + return new Option<>(null); return binder.apply(held); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { - return val -> { - return new Option<>(func.apply(val)); - }; + public <NewType> Function<ContainedType, IHolder<NewType>> + lift(final Function<ContainedType, NewType> func) { + return val -> new Option<>(func.apply(val)); } @Override - public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { - if(held == null) return new Option<>(null); + public <MappedType> IHolder<MappedType> + map(final Function<ContainedType, MappedType> mapper) { + if (held == null) + return new Option<>(null); return new Option<>(mapper.apply(held)); } @Override - public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { - if(held != null) { + public IHolder<ContainedType> + transform(final UnaryOperator<ContainedType> transformer) { + if (held != null) { held = transformer.apply(held); } @@ -55,8 +59,10 @@ public class Option<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { - if(held == null) return null; + public <UnwrappedType> UnwrappedType + unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { + if (held == null) + return null; return unwrapper.apply(held); } @@ -78,15 +84,20 @@ public class Option<ContainedType> implements IHolder<ContainedType> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof Option<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Option<?>)) + return false; final Option<?> other = (Option<?>) obj; - if(held == null) { - if(other.held != null) return false; - } else if(!held.equals(other.held)) return false; + if (held == null) { + if (other.held != null) + return false; + } else if (!held.equals(other.held)) + return false; return true; } diff --git a/src/main/java/bjc/data/Pair.java b/src/main/java/bjc/data/Pair.java index 3c1b7b5..610e89c 100644 --- a/src/main/java/bjc/data/Pair.java +++ b/src/main/java/bjc/data/Pair.java @@ -9,10 +9,10 @@ import java.util.function.Function; * @author ben * * @param <LeftType> - * The type of the left value. + * The type of the left value. * * @param <RightType> - * The type of the right value. + * The type of the right value. */ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { /* The left value. */ @@ -29,10 +29,10 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { * Create a new pair with both sides set to the specified values. * * @param left - * The value of the left side. + * The value of the left side. * * @param right - * The value of the right side. + * The value of the right side. */ public Pair(final LeftType left, final RightType right) { leftValue = left; @@ -42,15 +42,17 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( final BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { - if(binder == null) throw new NullPointerException("Binder must not be null."); + if (binder == null) + throw new NullPointerException("Binder must not be null."); return binder.apply(leftValue, rightValue); } @Override - public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( - final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { - if(leftBinder == null) throw new NullPointerException("Binder must not be null"); + public <BoundLeft> IPair<BoundLeft, RightType> + bindLeft(final Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + if (leftBinder == null) + throw new NullPointerException("Binder must not be null"); return leftBinder.apply(leftValue); } @@ -58,16 +60,19 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public <BoundRight> IPair<LeftType, BoundRight> bindRight( final Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { - if(rightBinder == null) throw new NullPointerException("Binder must not be null"); + if (rightBinder == null) + throw new NullPointerException("Binder must not be null"); return rightBinder.apply(rightValue); } @Override - public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - final IPair<OtherLeft, OtherRight> otherPair, - final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, - final BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { + public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> + IPair<CombinedLeft, CombinedRight> + combine(final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<RightType, OtherRight, + CombinedRight> rightCombiner) { return otherPair.bind((otherLeft, otherRight) -> { final CombinedLeft left = leftCombiner.apply(leftValue, otherLeft); final CombinedRight right = rightCombiner.apply(rightValue, otherRight); @@ -77,35 +82,44 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { } @Override - public <NewLeft> IPair<NewLeft, RightType> mapLeft(final Function<LeftType, NewLeft> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <NewLeft> IPair<NewLeft, RightType> + mapLeft(final Function<LeftType, NewLeft> mapper) { + if (mapper == null) + throw new NullPointerException("Mapper must not be null"); return new Pair<>(mapper.apply(leftValue), rightValue); } @Override - public <NewRight> IPair<LeftType, NewRight> mapRight(final Function<RightType, NewRight> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <NewRight> IPair<LeftType, NewRight> + mapRight(final Function<RightType, NewRight> mapper) { + if (mapper == null) + throw new NullPointerException("Mapper must not be null"); return new Pair<>(leftValue, mapper.apply(rightValue)); } @Override - public <MergedType> MergedType merge(final BiFunction<LeftType, RightType, MergedType> merger) { - if(merger == null) throw new NullPointerException("Merger must not be null"); + public <MergedType> MergedType + merge(final BiFunction<LeftType, RightType, MergedType> merger) { + if (merger == null) + throw new NullPointerException("Merger must not be null"); return merger.apply(leftValue, rightValue); } @Override public String toString() { - return String.format("Pair [leftValue='%s', rightValue='%s']", leftValue, rightValue); + return String.format("Pair [leftValue='%s', rightValue='%s']", leftValue, + rightValue); } + @Override public LeftType getLeft() { return leftValue; } + @Override public RightType getRight() { return rightValue; } @@ -123,19 +137,26 @@ public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof Pair<?, ?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Pair<?, ?>)) + return false; final Pair<?, ?> other = (Pair<?, ?>) obj; - if(leftValue == null) { - if(other.leftValue != null) return false; - } else if(!leftValue.equals(other.leftValue)) return false; - - if(rightValue == null) { - if(other.rightValue != null) return false; - } else if(!rightValue.equals(other.rightValue)) return false; + if (leftValue == null) { + if (other.leftValue != null) + return false; + } else if (!leftValue.equals(other.leftValue)) + return false; + + if (rightValue == null) { + if (other.rightValue != null) + return false; + } else if (!rightValue.equals(other.rightValue)) + return false; return true; } diff --git a/src/main/java/bjc/data/QueuedIterator.java b/src/main/java/bjc/data/QueuedIterator.java index ebacb52..f10014e 100644 --- a/src/main/java/bjc/data/QueuedIterator.java +++ b/src/main/java/bjc/data/QueuedIterator.java @@ -6,10 +6,11 @@ import java.util.Iterator; /** * An iterator that supports queuing elements after/before the current iterator; - * + * * @author bjculkin * - * @param <E> The type of element this iterator iterates over + * @param <E> + * The type of element this iterator iterates over */ public class QueuedIterator<E> implements Iterator<E> { private Iterator<E> cur; @@ -18,7 +19,7 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Static method for constructing iterators. - * + * * @return A queued iterator. */ public static <E> QueuedIterator<E> queued() { @@ -27,9 +28,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Static method for constructing iterators. - * + * * @param vals - * The values to iterate over. + * The values to iterate over. * * @return A queued iterator. */ @@ -40,9 +41,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Static method for constructing iterators. - * + * * @param itrs - * The iterators to use. + * The iterators to use. * * @return A queued iterator over the provided iterators. */ @@ -53,9 +54,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Static method for constructing iterators. - * + * * @param itrs - * The iterables to use. + * The iterables to use. * * @return A queued iterator over the provided iterables. */ @@ -73,9 +74,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Create a new queued iterator with a set of initial sources. - * + * * @param inits - * The set of initial iterators to use. + * The set of initial iterators to use. */ @SafeVarargs public QueuedIterator(Iterator<E>... inits) { @@ -88,9 +89,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Create a new queued iterator with a set of initial sources. - * + * * @param inits - * The set of initial iterables to use. + * The set of initial iterables to use. */ @SafeVarargs public QueuedIterator(Iterable<E>... inits) { @@ -103,9 +104,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Create a new queued iterator with a set of initial values. - * + * * @param vals - * The set of initial values to use. + * The set of initial values to use. */ @SafeVarargs public QueuedIterator(E... vals) { @@ -114,9 +115,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Add a new iterator who we will iterate through first. - * + * * @param itr - * The iterator to go through first. + * The iterator to go through first. */ public void before(Iterator<E> itr) { pending.push(cur); @@ -126,19 +127,19 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Add a new iterable who we will iterate through first. - * + * * @param itr - * The iterable to go through first. + * The iterable to go through first. */ public void before(Iterable<E> itr) { before(itr.iterator()); } - + /** * Add a new set of values who we will iterate through first. - * + * * @param vals - * Values to iterate over first. + * Values to iterate over first. */ public void before(@SuppressWarnings("unchecked") E... vals) { before(new ArrayIterator<>(vals)); @@ -146,9 +147,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Add a new iterator who we will iterate through next. - * + * * @param itr - * The iterator to go through next. + * The iterator to go through next. */ public void after(Iterator<E> itr) { pending.push(itr); @@ -156,9 +157,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Add a new iterable who we will iterate through next. - * + * * @param itr - * The iterable to go through next. + * The iterable to go through next. */ public void after(Iterable<E> itr) { after(itr.iterator()); @@ -166,19 +167,19 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Add a new set of values who we will iterate through next. - * + * * @param vals - * The values to iterate over next. + * The values to iterate over next. */ public void after(@SuppressWarnings("unchecked") E... vals) { after(new ArrayIterator<>(vals)); } - + /** * Add a new iterator who we will iterate through last. - * + * * @param itr - * The iterator to go through last. + * The iterator to go through last. */ public void last(Iterator<E> itr) { pending.add(itr); @@ -186,9 +187,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Add a new iterable who we will iterate through last. - * + * * @param itr - * The iterable to go through last. + * The iterable to go through last. */ public void last(Iterable<E> itr) { last(itr.iterator()); @@ -196,9 +197,9 @@ public class QueuedIterator<E> implements Iterator<E> { /** * Add a new set of values who we will iterate through last. - * + * * @param vals - * The values we will iterate over. + * The values we will iterate over. */ public void last(@SuppressWarnings("unchecked") E... vals) { last(new ArrayIterator<>(vals)); @@ -207,7 +208,8 @@ public class QueuedIterator<E> implements Iterator<E> { @Override public boolean hasNext() { while (cur == null || !cur.hasNext()) { - if (pending.isEmpty()) return false; + if (pending.isEmpty()) + return false; cur = pending.pop(); } @@ -218,7 +220,8 @@ public class QueuedIterator<E> implements Iterator<E> { @Override public E next() { while (cur == null || !cur.hasNext()) { - if (pending.isEmpty()) return null; + if (pending.isEmpty()) + return null; cur = pending.pop(); } diff --git a/src/main/java/bjc/data/SingleIterator.java b/src/main/java/bjc/data/SingleIterator.java index 3144447..1598774 100644 --- a/src/main/java/bjc/data/SingleIterator.java +++ b/src/main/java/bjc/data/SingleIterator.java @@ -8,7 +8,7 @@ import java.util.Iterator; * @author EVE * * @param <T> - * The type of the item. + * The type of the item. */ public class SingleIterator<T> implements Iterator<T> { /* The item being held. */ @@ -20,7 +20,7 @@ public class SingleIterator<T> implements Iterator<T> { * Create a iterator that yields a single item. * * @param item - * The item to yield. + * The item to yield. */ public SingleIterator(final T item) { itm = item; diff --git a/src/main/java/bjc/data/SingleSupplier.java b/src/main/java/bjc/data/SingleSupplier.java index bc1fbc4..010b06e 100644 --- a/src/main/java/bjc/data/SingleSupplier.java +++ b/src/main/java/bjc/data/SingleSupplier.java @@ -10,7 +10,7 @@ import java.util.function.Supplier; * @author ben * * @param <T> - * The supplied type + * The supplied type */ public class SingleSupplier<T> implements Supplier<T> { /* The next supplier ID. */ @@ -26,8 +26,8 @@ public class SingleSupplier<T> implements Supplier<T> { * The place where the supplier was instantiated. * * @NOTE This is both slow to create, and generally bad practice to keep - * exceptions around without throwing them. However, it is very useful - * to find where the first instantiation was. + * exceptions around without throwing them. However, it is very useful to find + * where the first instantiation was. */ private Exception instSite; @@ -35,7 +35,7 @@ public class SingleSupplier<T> implements Supplier<T> { * Create a new single supplier from an existing value. * * @param supp - * The supplier to give a single value from. + * The supplier to give a single value from. */ public SingleSupplier(final Supplier<T> supp) { source = supp; @@ -47,9 +47,10 @@ public class SingleSupplier<T> implements Supplier<T> { @Override public T get() { - if(gotten == true) { + if (gotten == true) { final String msg = String.format( - "Attempted to retrieve value more than once from single supplier #%d", id); + "Attempted to retrieve value more than once from single supplier #%d", + id); final IllegalStateException isex = new IllegalStateException(msg); @@ -62,7 +63,7 @@ public class SingleSupplier<T> implements Supplier<T> { try { throw new IllegalStateException("Previous instantiation here."); - } catch(final IllegalStateException isex) { + } catch (final IllegalStateException isex) { instSite = isex; } @@ -71,6 +72,7 @@ public class SingleSupplier<T> implements Supplier<T> { @Override public String toString() { - return String.format("SingleSupplier [source='%s', gotten=%s, id=%s]", source, gotten, id); + return String.format("SingleSupplier [source='%s', gotten=%s, id=%s]", source, + gotten, id); } } diff --git a/src/main/java/bjc/data/Toggle.java b/src/main/java/bjc/data/Toggle.java index 14c77d3..17c5a8e 100644 --- a/src/main/java/bjc/data/Toggle.java +++ b/src/main/java/bjc/data/Toggle.java @@ -6,12 +6,12 @@ package bjc.data; * @author EVE * * @param <E> - * The value stored in the toggle. + * The value stored in the toggle. */ public interface Toggle<E> { /** - * Retrieve the currently-aligned value of this toggle, and swap the - * value to the new one. + * Retrieve the currently-aligned value of this toggle, and swap the value to + * the new one. * * @return The previously-aligned value. */ @@ -28,7 +28,7 @@ public interface Toggle<E> { * Change the alignment of the toggle. * * @param isLeft - * Whether the toggle should be left-aligned or not. + * Whether the toggle should be left-aligned or not. */ void set(boolean isLeft); } diff --git a/src/main/java/bjc/data/TopDownTransformIterator.java b/src/main/java/bjc/data/TopDownTransformIterator.java index 66faafe..3b4b997 100644 --- a/src/main/java/bjc/data/TopDownTransformIterator.java +++ b/src/main/java/bjc/data/TopDownTransformIterator.java @@ -12,30 +12,31 @@ import java.util.function.Function; /* * @TODO 10/11/17 Ben Culkin :TopDownStep - * + * * Figure out what is broken with this, and fix it so that step-wise * iteration works correctly. */ /** * An iterative top-down transform of a tree. - * + * * @author EVE * * @param <ContainedType> - * The type of the nodes in the tree. + * The type of the nodes in the tree. */ -public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<ContainedType>> { +public class TopDownTransformIterator<ContainedType> + implements Iterator<ITree<ContainedType>> { /** * Alias type for a tree transformation. - * + * * @author student * * @param <ContainedType> - * The type contained in the tree. + * The type contained in the tree. */ - public interface TreeTransform<ContainedType> - extends BiFunction<ITree<ContainedType>, Consumer<Iterator<ITree<ContainedType>>>, ITree<ContainedType>> { + public interface TreeTransform<ContainedType> extends BiFunction<ITree<ContainedType>, + Consumer<Iterator<ITree<ContainedType>>>, ITree<ContainedType>> { // Alias type; no body is needed } @@ -64,32 +65,34 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C /** * Create a new tree iterator. - * + * * @param pickr - * The function to use to pick how to process nodes. + * The function to use to pick how to process nodes. * @param transfrm - * The transform to apply to the nodes. + * The transform to apply to the nodes. * @param tree - * The tree to transform. + * The tree to transform. */ - public TopDownTransformIterator(final Function<ContainedType, TopDownTransformResult> pickr, - final TreeTransform<ContainedType> transfrm, final ITree<ContainedType> tree) { + public TopDownTransformIterator( + final Function<ContainedType, TopDownTransformResult> pickr, + final TreeTransform<ContainedType> transfrm, + final ITree<ContainedType> tree) { preParent = tree; - preChildren = new LinkedList<>(); + preChildren = new LinkedList<>(); postChildren = new LinkedList<>(); - toYield = new LinkedList<>(); + toYield = new LinkedList<>(); - picker = pickr; + picker = pickr; transform = transfrm; - done = false; + done = false; initial = true; } /** * Add a set of nodes to yield. - * + * * @param src * The nodes to yield. */ @@ -108,10 +111,10 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C /** * Get the next yielded value. - * + * * @param val * The sentinel value to yield. - * + * * @return The next yielded value. */ public ITree<ContainedType> flushYields(final ITree<ContainedType> val) { @@ -158,7 +161,7 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C if (yeld != null) return yeld; } - + if (initial) { /* * Get the way we are transforming. @@ -200,9 +203,11 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } done = true; - return flushYields(transform.apply(new Tree<>(preParent.getHead()), this::addYield)); + return flushYields( + transform.apply(new Tree<>(preParent.getHead()), this::addYield)); case PULLUP: - final ITree<ContainedType> intRes = transform.apply(preParent, this::addYield); + final ITree<ContainedType> intRes + = transform.apply(preParent, this::addYield); postParent = new Tree<>(intRes.getHead()); @@ -228,10 +233,11 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C if (curChild == null || !curChild.hasNext()) { if (preChildren.size() != 0) { - curChild = new TopDownTransformIterator<>(picker, transform, preChildren.pop()); + curChild = new TopDownTransformIterator<>(picker, transform, + preChildren.pop()); final ITree<ContainedType> res = curChild.next(); - //System.out.println("\t\tTRACE: adding node " + res + " to children"); + // System.out.println("\t\tTRACE: adding node " + res + " to children"); postChildren.add(res); return flushYields(res); @@ -242,7 +248,8 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C if (postParent == null) { res = new Tree<>(preParent.getHead()); - //System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + res); + // System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + + // res); for (final ITree<ContainedType> child : postChildren) { res.addChild(child); @@ -253,7 +260,8 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } else { res = postParent; - //System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + res); + // System.out.println("\t\tTRACE: adding nodes " + postChildren + " to " + + // res); for (final ITree<ContainedType> child : postChildren) { res.addChild(child); } @@ -264,7 +272,7 @@ public class TopDownTransformIterator<ContainedType> implements Iterator<ITree<C } final ITree<ContainedType> res = curChild.next(); - //System.out.println("\t\tTRACE: adding node " + res + " to children"); + // System.out.println("\t\tTRACE: adding node " + res + " to children"); postChildren.add(res); return flushYields(res); diff --git a/src/main/java/bjc/data/TransformIterator.java b/src/main/java/bjc/data/TransformIterator.java index 0fc127a..29f91e2 100644 --- a/src/main/java/bjc/data/TransformIterator.java +++ b/src/main/java/bjc/data/TransformIterator.java @@ -9,10 +9,10 @@ import java.util.function.Function; * @author EVE * * @param <S> - * The source iterator type. + * The source iterator type. * * @param <D> - * The destination iterator type. + * The destination iterator type. */ public class TransformIterator<S, D> implements Iterator<D> { /* Our source of values. */ @@ -24,10 +24,10 @@ public class TransformIterator<S, D> implements Iterator<D> { * Create a new transform iterator. * * @param source - * The source iterator to use. + * The source iterator to use. * * @param transform - * The transform to apply. + * The transform to apply. */ public TransformIterator(final Iterator<S> source, final Function<S, D> transform) { this.source = source; diff --git a/src/main/java/bjc/data/Tree.java b/src/main/java/bjc/data/Tree.java index d9ccb34..27dcf11 100644 --- a/src/main/java/bjc/data/Tree.java +++ b/src/main/java/bjc/data/Tree.java @@ -16,7 +16,7 @@ import bjc.funcdata.bst.TreeLinearizationMethod; * @author ben * * @param <ContainedType> - * The type contained in the tree. + * The type contained in the tree. */ public class Tree<ContainedType> implements ITree<ContainedType> { /* The data/label for this node. */ @@ -27,10 +27,9 @@ public class Tree<ContainedType> implements ITree<ContainedType> { /* Whether this node has children. */ /* - * @NOTE Why have both this boolean and childCount? Why not just do a - * childCount == 0 whenever you'd check hasChildren? - * - Because hasChildren is set once and not reset, and really what - * it indicates is that children has been allocated. + * @NOTE Why have both this boolean and childCount? Why not just do a childCount + * == 0 whenever you'd check hasChildren? - Because hasChildren is set once and + * not reset, and really what it indicates is that children has been allocated. */ private boolean hasChildren; /* The number of children this node has. */ @@ -52,7 +51,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * Create a new leaf node in a tree. * * @param leaf - * The data to store as a leaf node. + * The data to store as a leaf node. */ public Tree(final ContainedType leaf) { data = leaf; @@ -66,10 +65,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * Create a new tree node with the specified children. * * @param leaf - * The data to hold in this node. + * The data to hold in this node. * * @param childrn - * A list of children for this node. + * A list of children for this node. */ public Tree(final ContainedType leaf, final IList<ITree<ContainedType>> childrn) { this(leaf); @@ -85,10 +84,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { * Create a new tree node with the specified children. * * @param leaf - * The data to hold in this node. + * The data to hold in this node. * * @param childrn - * A list of children for this node. + * A list of children for this node. */ @SafeVarargs public Tree(final ContainedType leaf, final ITree<ContainedType>... childrn) { @@ -100,7 +99,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { children = new FunctionalList<>(); - for(final ITree<ContainedType> child : childrn) { + for (final ITree<ContainedType> child : childrn) { children.add(child); childCount++; @@ -114,7 +113,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public void addChild(final ITree<ContainedType> child) { - if(hasChildren == false) { + if (hasChildren == false) { hasChildren = true; children = new FunctionalList<>(); @@ -127,7 +126,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public void prependChild(final ITree<ContainedType> child) { - if(hasChildren == false) { + if (hasChildren == false) { hasChildren = true; children = new FunctionalList<>(); @@ -140,7 +139,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public void doForChildren(final Consumer<ITree<ContainedType>> action) { - if(childCount > 0) { + if (childCount > 0) { children.forEach(action); } } @@ -152,23 +151,25 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public int revFind(final Predicate<ITree<ContainedType>> childPred) { - if(childCount == 0) { + if (childCount == 0) { return -1; } - for(int i = childCount - 1; i >= 0; i--) { - if(childPred.test(getChild(i))) return i; + for (int i = childCount - 1; i >= 0; i--) { + if (childPred.test(getChild(i))) + return i; } return -1; } @Override - public void traverse(final TreeLinearizationMethod linearizationMethod, final Consumer<ContainedType> action) { - if(hasChildren) { - switch(linearizationMethod) { + public void traverse(final TreeLinearizationMethod linearizationMethod, + final Consumer<ContainedType> action) { + if (hasChildren) { + switch (linearizationMethod) { case INORDER: - if(childCount != 2) { + if (childCount != 2) { final String msg = "Can only do in-order traversal for binary trees."; throw new IllegalArgumentException(msg); @@ -181,14 +182,14 @@ public class Tree<ContainedType> implements ITree<ContainedType> { children.getByIndex(1).traverse(linearizationMethod, action); break; case POSTORDER: - children.forEach((child) -> child.traverse(linearizationMethod, action)); + children.forEach(child -> child.traverse(linearizationMethod, action)); action.accept(data); break; case PREORDER: action.accept(data); - children.forEach((child) -> child.traverse(linearizationMethod, action)); + children.forEach(child -> child.traverse(linearizationMethod, action)); break; default: break; @@ -200,19 +201,21 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public <NewType, ReturnedType> ReturnedType collapse(final Function<ContainedType, NewType> leafTransform, + public <NewType, ReturnedType> ReturnedType collapse( + final Function<ContainedType, NewType> leafTransform, final BiFunction<ContainedType, IList<NewType>, NewType> nodeCollapser, final Function<NewType, ReturnedType> resultTransformer) { return resultTransformer.apply(internalCollapse(leafTransform, nodeCollapser)); } @Override - public ITree<ContainedType> flatMapTree(final Function<ContainedType, ITree<ContainedType>> mapper) { - if(hasChildren) { + public ITree<ContainedType> + flatMapTree(final Function<ContainedType, ITree<ContainedType>> mapper) { + if (hasChildren) { final ITree<ContainedType> flatMappedData = mapper.apply(data); - final IList<ITree<ContainedType>> mappedChildren = children - .map(child -> child.flatMapTree(mapper)); + final IList<ITree<ContainedType>> mappedChildren + = children.map(child -> child.flatMapTree(mapper)); mappedChildren.forEach(flatMappedData::addChild); @@ -225,13 +228,14 @@ public class Tree<ContainedType> implements ITree<ContainedType> { /* * Do a collapse of this tree. * - * @NOTE Why is this protected? I can't see any good reason someone'd - * want to override it. + * @NOTE Why is this protected? I can't see any good reason someone'd want to + * override it. */ - protected <NewType> NewType internalCollapse(final Function<ContainedType, NewType> leafTransform, + protected <NewType> NewType internalCollapse( + final Function<ContainedType, NewType> leafTransform, final BiFunction<ContainedType, IList<NewType>, NewType> nodeCollapser) { - if(hasChildren) { + if (hasChildren) { final IList<NewType> collapsedChildren = children.map(child -> { final NewType collapsed = child.collapse(leafTransform, nodeCollapser, subTreeVal -> subTreeVal); @@ -245,9 +249,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { return leafTransform.apply(data); } - protected void internalToString(final StringBuilder builder, final int indentLevel, final boolean initial) { - if(!initial) { - for(int i = 0; i < indentLevel; i++) { + protected void internalToString(final StringBuilder builder, final int indentLevel, + final boolean initial) { + if (!initial) { + for (int i = 0; i < indentLevel; i++) { builder.append(">\t"); } } @@ -258,14 +263,14 @@ public class Tree<ContainedType> implements ITree<ContainedType> { builder.append(data == null ? "(null)" : data.toString()); builder.append("\n"); - if(hasChildren) { + if (hasChildren) { children.forEach(child -> { - if(child instanceof Tree<?>) { + if (child instanceof Tree<?>) { final Tree<ContainedType> kid = (Tree<ContainedType>) child; kid.internalToString(builder, indentLevel + 1, false); } else { - for(int i = 0; i < indentLevel + 1; i++) { + for (int i = 0; i < indentLevel + 1; i++) { builder.append(">\t"); } @@ -278,12 +283,11 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public <MappedType> ITree<MappedType> rebuildTree(final Function<ContainedType, MappedType> leafTransformer, + public <MappedType> ITree<MappedType> rebuildTree( + final Function<ContainedType, MappedType> leafTransformer, final Function<ContainedType, MappedType> operatorTransformer) { - if(hasChildren) { - final IList<ITree<MappedType>> mappedChildren = children.map(child -> { - return child.rebuildTree(leafTransformer, operatorTransformer); - }); + if (hasChildren) { + final IList<ITree<MappedType>> mappedChildren = children.map(child -> child.rebuildTree(leafTransformer, operatorTransformer)); final MappedType mapData = operatorTransformer.apply(data); return new Tree<>(mapData, mappedChildren); @@ -295,7 +299,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public void selectiveTransform(final Predicate<ContainedType> nodePicker, final UnaryOperator<ContainedType> transformer) { - if(hasChildren) { + if (hasChildren) { children.forEach(child -> child.selectiveTransform(nodePicker, transformer)); } else { data = transformer.apply(data); @@ -308,14 +312,14 @@ public class Tree<ContainedType> implements ITree<ContainedType> { final UnaryOperator<ITree<ContainedType>> transformer) { final TopDownTransformResult transformResult = transformPicker.apply(data); - switch(transformResult) { + switch (transformResult) { case PASSTHROUGH: ITree<ContainedType> result = new Tree<>(data); - if(hasChildren) { + if (hasChildren) { children.forEach(child -> { - final ITree<ContainedType> kid = child.topDownTransform(transformPicker, - transformer); + final ITree<ContainedType> kid + = child.topDownTransform(transformPicker, transformer); result.addChild(kid); }); @@ -331,10 +335,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { case PUSHDOWN: result = new Tree<>(data); - if(hasChildren) { + if (hasChildren) { children.forEach(child -> { - final ITree<ContainedType> kid = child.topDownTransform(transformPicker, - transformer); + final ITree<ContainedType> kid + = child.topDownTransform(transformPicker, transformer); result.addChild(kid); }); @@ -347,14 +351,16 @@ public class Tree<ContainedType> implements ITree<ContainedType> { result = new Tree<>(intermediateResult.getHead()); intermediateResult.doForChildren(child -> { - final ITree<ContainedType> kid = child.topDownTransform(transformPicker, transformer); + final ITree<ContainedType> kid + = child.topDownTransform(transformPicker, transformer); result.addChild(kid); }); return result; default: - final String msg = String.format("Recieved unknown transform result type %s", transformResult); + final String msg = String.format("Recieved unknown transform result type %s", + transformResult); throw new IllegalArgumentException(msg); } @@ -363,7 +369,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public <TransformedType> TransformedType transformChild(final int childNo, final Function<ITree<ContainedType>, TransformedType> transformer) { - if(childNo < 0 || childNo > childCount - 1) { + if (childNo < 0 || childNo > childCount - 1) { final String msg = String.format("Child index #%d is invalid", childNo); throw new IllegalArgumentException(msg); @@ -375,8 +381,8 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public <TransformedType> TransformedType transformHead( - final Function<ContainedType, TransformedType> transformer) { + public <TransformedType> TransformedType + transformHead(final Function<ContainedType, TransformedType> transformer) { return transformer.apply(data); } @@ -411,21 +417,29 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof Tree<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Tree<?>)) + return false; final Tree<?> other = (Tree<?>) obj; - if(data == null) { - if(other.data != null) return false; - } else if(!data.equals(other.data)) return false; + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; - if(childCount != other.childCount) return false; + if (childCount != other.childCount) + return false; - if(children == null) { - if(other.children != null) return false; - } else if(!children.equals(other.children)) return false; + if (children == null) { + if (other.children != null) + return false; + } else if (!children.equals(other.children)) + return false; return true; } diff --git a/src/main/java/bjc/data/ValueToggle.java b/src/main/java/bjc/data/ValueToggle.java index e79169f..041a2d5 100644 --- a/src/main/java/bjc/data/ValueToggle.java +++ b/src/main/java/bjc/data/ValueToggle.java @@ -6,7 +6,7 @@ package bjc.data; * @author EVE * * @param <E> - * The type of value to toggle between. + * The type of value to toggle between. */ public class ValueToggle<E> implements Toggle<E> { /* Our left value. */ @@ -22,10 +22,10 @@ public class ValueToggle<E> implements Toggle<E> { * All toggles start right-aligned. * * @param left - * The value when the toggle is left-aligned. + * The value when the toggle is left-aligned. * * @param right - * The value when the toggle is right-aligned. + * The value when the toggle is right-aligned. */ public ValueToggle(final E left, final E right) { lft = left; @@ -37,7 +37,7 @@ public class ValueToggle<E> implements Toggle<E> { @Override public E get() { - if(alignment.get()) { + if (alignment.get()) { return lft; } @@ -46,7 +46,7 @@ public class ValueToggle<E> implements Toggle<E> { @Override public E peek() { - if(alignment.peek()) { + if (alignment.peek()) { return lft; } diff --git a/src/main/java/bjc/data/internals/BoundLazy.java b/src/main/java/bjc/data/internals/BoundLazy.java index 728af8e..9c984eb 100644 --- a/src/main/java/bjc/data/internals/BoundLazy.java +++ b/src/main/java/bjc/data/internals/BoundLazy.java @@ -15,7 +15,8 @@ import bjc.funcdata.IList; * @author Ben Culkin */ @SuppressWarnings("javadoc") -public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundContainedType> { +public class BoundLazy<OldType, BoundContainedType> + implements IHolder<BoundContainedType> { /* The old value. */ private final Supplier<IHolder<OldType>> oldSupplier; @@ -29,16 +30,17 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont private boolean holderBound; /* Transformations currently pending on the bound value. */ - private final IList<UnaryOperator<BoundContainedType>> actions = new FunctionalList<>(); + private final IList<UnaryOperator<BoundContainedType>> actions + = new FunctionalList<>(); /** * Create a new bound lazy value. * * @param supp - * The supplier of the old value. + * The supplier of the old value. * * @param binder - * The function to use to bind the old value to the new one. + * The function to use to bind the old value to the new one. */ public BoundLazy(final Supplier<IHolder<OldType>> supp, final Function<OldType, IHolder<BoundContainedType>> binder) { @@ -47,11 +49,14 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont } @Override - public <BoundType> IHolder<BoundType> bind(final Function<BoundContainedType, IHolder<BoundType>> bindr) { - if(bindr == null) throw new NullPointerException("Binder must not be null"); + public <BoundType> IHolder<BoundType> + bind(final Function<BoundContainedType, IHolder<BoundType>> bindr) { + if (bindr == null) + throw new NullPointerException("Binder must not be null"); /* Prepare a list of pending actions. */ - final IList<UnaryOperator<BoundContainedType>> pendingActions = new FunctionalList<>(); + final IList<UnaryOperator<BoundContainedType>> pendingActions + = new FunctionalList<>(); actions.forEach(pendingActions::add); /* Create the new supplier of a value. */ @@ -59,35 +64,37 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont IHolder<BoundContainedType> oldHolder = boundHolder; /* Bind the value if it hasn't been bound before. */ - if(!holderBound) { + if (!holderBound) { oldHolder = oldSupplier.get().unwrap(binder); } /* Apply all the pending actions. */ - return pendingActions.reduceAux(oldHolder, (action, state) -> { - return state.transform(action); - }, (value) -> value); + return pendingActions.reduceAux(oldHolder, (action, state) -> state.transform(action), value -> value); }; return new BoundLazy<>(typeSupplier, bindr); } @Override - public <NewType> Function<BoundContainedType, IHolder<NewType>> lift( - final Function<BoundContainedType, NewType> func) { - if(func == null) throw new NullPointerException("Function to lift must not be null"); + public <NewType> Function<BoundContainedType, IHolder<NewType>> + lift(final Function<BoundContainedType, NewType> func) { + if (func == null) + throw new NullPointerException("Function to lift must not be null"); - return (val) -> { + return val -> { return new Lazy<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(final Function<BoundContainedType, MappedType> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <MappedType> IHolder<MappedType> + map(final Function<BoundContainedType, MappedType> mapper) { + if (mapper == null) + throw new NullPointerException("Mapper must not be null"); /* Prepare a list of pending actions. */ - final IList<UnaryOperator<BoundContainedType>> pendingActions = new FunctionalList<>(); + final IList<UnaryOperator<BoundContainedType>> pendingActions + = new FunctionalList<>(); actions.forEach(pendingActions::add); /* Prepare the new supplier. */ @@ -95,14 +102,12 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont IHolder<BoundContainedType> oldHolder = boundHolder; /* Bound the value if it hasn't been bound. */ - if(!holderBound) { + if (!holderBound) { oldHolder = oldSupplier.get().unwrap(binder); } /* Apply pending actions. */ - return pendingActions.reduceAux(oldHolder.getValue(), (action, state) -> { - return action.apply(state); - }, (value) -> mapper.apply(value)); + return pendingActions.reduceAux(oldHolder.getValue(), (action, state) -> action.apply(state), value -> mapper.apply(value)); }; return new Lazy<>(typeSupplier); @@ -110,14 +115,17 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont @Override public String toString() { - if(holderBound) return boundHolder.toString(); + if (holderBound) + return boundHolder.toString(); return "(unmaterialized)"; } @Override - public IHolder<BoundContainedType> transform(final UnaryOperator<BoundContainedType> transformer) { - if(transformer == null) throw new NullPointerException("Transformer must not be null"); + public IHolder<BoundContainedType> + transform(final UnaryOperator<BoundContainedType> transformer) { + if (transformer == null) + throw new NullPointerException("Transformer must not be null"); actions.add(transformer); @@ -125,10 +133,12 @@ public class BoundLazy<OldType, BoundContainedType> implements IHolder<BoundCont } @Override - public <UnwrappedType> UnwrappedType unwrap(final Function<BoundContainedType, UnwrappedType> unwrapper) { - if(unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); + public <UnwrappedType> UnwrappedType + unwrap(final Function<BoundContainedType, UnwrappedType> unwrapper) { + if (unwrapper == null) + throw new NullPointerException("Unwrapper must not be null"); - if(!holderBound) { + if (!holderBound) { boundHolder = oldSupplier.get().unwrap(binder::apply); } diff --git a/src/main/java/bjc/data/internals/BoundLazyPair.java b/src/main/java/bjc/data/internals/BoundLazyPair.java index 105b410..e081c04 100644 --- a/src/main/java/bjc/data/internals/BoundLazyPair.java +++ b/src/main/java/bjc/data/internals/BoundLazyPair.java @@ -15,7 +15,8 @@ import bjc.data.LazyPair; * @author Ben Culkin */ @SuppressWarnings("javadoc") -public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPair<NewLeft, NewRight> { +public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> + implements IPair<NewLeft, NewRight> { /* The supplier of the left value. */ private final Supplier<OldLeft> leftSupplier; /* The supplier of the right value. */ @@ -34,16 +35,17 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai * Create a new bound lazy pair. * * @param leftSupp - * The supplier for the left value. + * The supplier for the left value. * * @param rightSupp - * The supplier for the right value. + * The supplier for the right value. * * @param bindr - * The function to use to bind the left and right into a new - * pair. + * The function to use to bind the left and right into a new + * pair. */ - public BoundLazyPair(final Supplier<OldLeft> leftSupp, final Supplier<OldRight> rightSupp, + public BoundLazyPair(final Supplier<OldLeft> leftSupp, + final Supplier<OldRight> rightSupp, final BiFunction<OldLeft, OldRight, IPair<NewLeft, NewRight>> bindr) { leftSupplier = leftSupp; rightSupplier = rightSupp; @@ -53,54 +55,53 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( final BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) { - if(bindr == null) throw new NullPointerException("Binder must not be null"); + if (bindr == null) + throw new NullPointerException("Binder must not be null"); final IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(boundPair); final IHolder<Boolean> newPairMade = new Identity<>(pairBound); final Supplier<NewLeft> leftSupp = () -> { - if(!newPairMade.getValue()) { + if (!newPairMade.getValue()) { /* - * If the pair hasn't been bound before, bind - * it. + * If the pair hasn't been bound before, bind it. */ newPair.replace(binder.apply(leftSupplier.get(), rightSupplier.get())); newPairMade.replace(true); } - return newPair.unwrap((pair) -> pair.getLeft()); + return newPair.unwrap(pair -> pair.getLeft()); }; final Supplier<NewRight> rightSupp = () -> { - if(!newPairMade.getValue()) { + if (!newPairMade.getValue()) { /* - * If the pair hasn't been bound before, bind - * it. + * If the pair hasn't been bound before, bind it. */ newPair.replace(binder.apply(leftSupplier.get(), rightSupplier.get())); newPairMade.replace(true); } - return newPair.unwrap((pair) -> pair.getRight()); + return newPair.unwrap(pair -> pair.getRight()); }; return new BoundLazyPair<>(leftSupp, rightSupp, bindr); } @Override - public <BoundLeft> IPair<BoundLeft, NewRight> bindLeft( - final Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) { - if(leftBinder == null) throw new NullPointerException("Left binder must not be null"); + public <BoundLeft> IPair<BoundLeft, NewRight> + bindLeft(final Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) { + if (leftBinder == null) + throw new NullPointerException("Left binder must not be null"); final Supplier<NewLeft> leftSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if(!pairBound) { + if (!pairBound) { /* - * If the pair hasn't been bound before, bind - * it. + * If the pair hasn't been bound before, bind it. */ newPair = binder.apply(leftSupplier.get(), rightSupplier.get()); } @@ -112,17 +113,17 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai } @Override - public <BoundRight> IPair<NewLeft, BoundRight> bindRight( - final Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { - if(rightBinder == null) throw new NullPointerException("Right binder must not be null"); + public <BoundRight> IPair<NewLeft, BoundRight> + bindRight(final Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { + if (rightBinder == null) + throw new NullPointerException("Right binder must not be null"); final Supplier<NewRight> rightSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if(!pairBound) { + if (!pairBound) { /* - * If the pair hasn't been bound before, bind - * it. + * If the pair hasn't been bound before, bind it. */ newPair = binder.apply(leftSupplier.get(), rightSupplier.get()); } @@ -134,35 +135,37 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai } @Override - public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - final IPair<OtherLeft, OtherRight> otherPair, - final BiFunction<NewLeft, OtherLeft, CombinedLeft> leftCombiner, - final BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { - if(otherPair == null) { + public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> + IPair<CombinedLeft, CombinedRight> + combine(final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<NewLeft, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { + if (otherPair == null) { throw new NullPointerException("Other pair must not be null"); - } else if(leftCombiner == null) { + } else if (leftCombiner == null) { throw new NullPointerException("Left combiner must not be null"); - } else if(rightCombiner == null) { + } else if (rightCombiner == null) { throw new NullPointerException("Right combiner must not be null"); } - return otherPair.bind((otherLeft, otherRight) -> { - return bind((leftVal, rightVal) -> { - CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); - CombinedRight cRight = rightCombiner.apply(rightVal, otherRight); + return otherPair.bind((otherLeft, otherRight) -> bind((leftVal, rightVal) -> { + CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); + CombinedRight cRight = rightCombiner.apply(rightVal, otherRight); - return new LazyPair<>(cLeft, cRight); - }); - }); + return new LazyPair<>(cLeft, cRight); + })); } @Override - public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(final Function<NewLeft, NewLeftType> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <NewLeftType> IPair<NewLeftType, NewRight> + mapLeft(final Function<NewLeft, NewLeftType> mapper) { + if (mapper == null) + throw new NullPointerException("Mapper must not be null"); final Supplier<NewLeftType> leftSupp = () -> { - if(!pairBound) { - final NewLeft leftVal = binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); + if (!pairBound) { + final NewLeft leftVal + = binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); return mapper.apply(leftVal); } @@ -171,7 +174,8 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai }; final Supplier<NewRight> rightSupp = () -> { - if(!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); + if (!pairBound) + return binder.apply(leftSupplier.get(), rightSupplier.get()).getRight(); return boundPair.getRight(); }; @@ -180,19 +184,22 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai } @Override - public <NewRightType> IPair<NewLeft, NewRightType> mapRight(final Function<NewRight, NewRightType> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <NewRightType> IPair<NewLeft, NewRightType> + mapRight(final Function<NewRight, NewRightType> mapper) { + if (mapper == null) + throw new NullPointerException("Mapper must not be null"); final Supplier<NewLeft> leftSupp = () -> { - if(!pairBound) return binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); + if (!pairBound) + return binder.apply(leftSupplier.get(), rightSupplier.get()).getLeft(); return boundPair.getLeft(); }; final Supplier<NewRightType> rightSupp = () -> { - if(!pairBound) { - final NewRight rightVal = binder.apply(leftSupplier.get(), rightSupplier.get()) - .getRight(); + if (!pairBound) { + final NewRight rightVal = binder + .apply(leftSupplier.get(), rightSupplier.get()).getRight(); return mapper.apply(rightVal); } @@ -204,10 +211,12 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai } @Override - public <MergedType> MergedType merge(final BiFunction<NewLeft, NewRight, MergedType> merger) { - if(merger == null) throw new NullPointerException("Merger must not be null"); + public <MergedType> MergedType + merge(final BiFunction<NewLeft, NewRight, MergedType> merger) { + if (merger == null) + throw new NullPointerException("Merger must not be null"); - if(!pairBound) { + if (!pairBound) { /* * If the pair isn't bound yet, bind it. */ @@ -221,7 +230,8 @@ public class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight> implements IPai @Override public String toString() { - if(pairBound) return boundPair.toString(); + if (pairBound) + return boundPair.toString(); return "(un-materialized)"; } diff --git a/src/main/java/bjc/data/internals/BoundListHolder.java b/src/main/java/bjc/data/internals/BoundListHolder.java index 8f8cab4..1193c8d 100644 --- a/src/main/java/bjc/data/internals/BoundListHolder.java +++ b/src/main/java/bjc/data/internals/BoundListHolder.java @@ -21,48 +21,58 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { * Create a new list of holders. * * @param toHold - * The list of holders to, well, hold. + * The list of holders to, well, hold. */ public BoundListHolder(final IList<IHolder<ContainedType>> toHold) { heldHolders = toHold; } @Override - public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { - if(binder == null) throw new NullPointerException("Binder must not be null"); + public <BoundType> IHolder<BoundType> + bind(final Function<ContainedType, IHolder<BoundType>> binder) { + if (binder == null) + throw new NullPointerException("Binder must not be null"); - final IList<IHolder<BoundType>> boundHolders = heldHolders.map((containedHolder) -> { - return containedHolder.bind(binder); - }); + final IList<IHolder<BoundType>> boundHolders + = heldHolders.map(containedHolder -> { + return containedHolder.bind(binder); + }); return new BoundListHolder<>(boundHolders); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { - if(func == null) throw new NullPointerException("Function to lift must not be null"); + public <NewType> Function<ContainedType, IHolder<NewType>> + lift(final Function<ContainedType, NewType> func) { + if (func == null) + throw new NullPointerException("Function to lift must not be null"); - return (val) -> { + return val -> { return new ListHolder<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { - if(mapper == null) throw new NullPointerException("Mapper must not be null"); + public <MappedType> IHolder<MappedType> + map(final Function<ContainedType, MappedType> mapper) { + if (mapper == null) + throw new NullPointerException("Mapper must not be null"); - final IList<IHolder<MappedType>> mappedHolders = heldHolders.map((containedHolder) -> { - return containedHolder.map(mapper); - }); + final IList<IHolder<MappedType>> mappedHolders + = heldHolders.map(containedHolder -> { + return containedHolder.map(mapper); + }); return new BoundListHolder<>(mappedHolders); } @Override - public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { - if(transformer == null) throw new NullPointerException("Transformer must not be null"); + public IHolder<ContainedType> + transform(final UnaryOperator<ContainedType> transformer) { + if (transformer == null) + throw new NullPointerException("Transformer must not be null"); - heldHolders.forEach((containedHolder) -> { + heldHolders.forEach(containedHolder -> { containedHolder.transform(transformer); }); @@ -70,8 +80,10 @@ public class BoundListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { - if(unwrapper == null) throw new NullPointerException("Unwrapper must not be null"); + public <UnwrappedType> UnwrappedType + unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { + if (unwrapper == null) + throw new NullPointerException("Unwrapper must not be null"); /* * @NOTE Is there another way we could want to do this? diff --git a/src/main/java/bjc/data/internals/HalfBoundLazyPair.java b/src/main/java/bjc/data/internals/HalfBoundLazyPair.java index 4f28012..6bcb6ae 100644 --- a/src/main/java/bjc/data/internals/HalfBoundLazyPair.java +++ b/src/main/java/bjc/data/internals/HalfBoundLazyPair.java @@ -23,7 +23,8 @@ import bjc.data.LazyPair; * @author Ben Culkin */ @SuppressWarnings("javadoc") -public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewLeft, NewRight> { +public class HalfBoundLazyPair<OldType, NewLeft, NewRight> + implements IPair<NewLeft, NewRight> { /* The supplier of the old value. */ private final Supplier<OldType> oldSupplier; @@ -39,10 +40,10 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL * Create a new half-bound lazy pair. * * @param oldSupp - * The supplier of the old value. + * The supplier of the old value. * * @param bindr - * The function to use to create the pair from the old value. + * The function to use to create the pair from the old value. */ public HalfBoundLazyPair(final Supplier<OldType> oldSupp, final Function<OldType, IPair<NewLeft, NewRight>> bindr) { @@ -57,35 +58,35 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL final IHolder<Boolean> newPairMade = new Identity<>(pairBound); final Supplier<NewLeft> leftSupp = () -> { - if(!newPairMade.getValue()) { + if (!newPairMade.getValue()) { /* Bind the pair if it hasn't been bound yet. */ newPair.replace(binder.apply(oldSupplier.get())); newPairMade.replace(true); } - return newPair.unwrap((pair) -> pair.getLeft()); + return newPair.unwrap(pair -> pair.getLeft()); }; final Supplier<NewRight> rightSupp = () -> { - if(!newPairMade.getValue()) { + if (!newPairMade.getValue()) { /* Bind the pair if it hasn't been bound yet. */ newPair.replace(binder.apply(oldSupplier.get())); newPairMade.replace(true); } - return newPair.unwrap((pair) -> pair.getRight()); + return newPair.unwrap(pair -> pair.getRight()); }; return new BoundLazyPair<>(leftSupp, rightSupp, bindr); } @Override - public <BoundLeft> IPair<BoundLeft, NewRight> bindLeft( - final Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) { + public <BoundLeft> IPair<BoundLeft, NewRight> + bindLeft(final Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) { final Supplier<NewLeft> leftSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if(!pairBound) { + if (!pairBound) { newPair = binder.apply(oldSupplier.get()); } @@ -96,12 +97,12 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL } @Override - public <BoundRight> IPair<NewLeft, BoundRight> bindRight( - final Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { + public <BoundRight> IPair<NewLeft, BoundRight> + bindRight(final Function<NewRight, IPair<NewLeft, BoundRight>> rightBinder) { final Supplier<NewRight> rightSupp = () -> { IPair<NewLeft, NewRight> newPair = boundPair; - if(!pairBound) { + if (!pairBound) { newPair = binder.apply(oldSupplier.get()); } @@ -112,24 +113,25 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL } @Override - public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - final IPair<OtherLeft, OtherRight> otherPair, - final BiFunction<NewLeft, OtherLeft, CombinedLeft> leftCombiner, - final BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { - return otherPair.bind((otherLeft, otherRight) -> { - return bind((leftVal, rightVal) -> { - CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); - CombinedRight cRight = rightCombiner.apply(rightVal, otherRight); - - return new LazyPair<>(cLeft, cRight); - }); - }); + public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> + IPair<CombinedLeft, CombinedRight> + combine(final IPair<OtherLeft, OtherRight> otherPair, + final BiFunction<NewLeft, OtherLeft, CombinedLeft> leftCombiner, + final BiFunction<NewRight, OtherRight, CombinedRight> rightCombiner) { + return otherPair.bind((otherLeft, otherRight) -> bind((leftVal, rightVal) -> { + CombinedLeft cLeft = leftCombiner.apply(leftVal, otherLeft); + CombinedRight cRight = rightCombiner.apply(rightVal, otherRight); + + return new LazyPair<>(cLeft, cRight); + })); } @Override - public <NewLeftType> IPair<NewLeftType, NewRight> mapLeft(final Function<NewLeft, NewLeftType> mapper) { + public <NewLeftType> IPair<NewLeftType, NewRight> + mapLeft(final Function<NewLeft, NewLeftType> mapper) { final Supplier<NewLeftType> leftSupp = () -> { - if(pairBound) return mapper.apply(boundPair.getLeft()); + if (pairBound) + return mapper.apply(boundPair.getLeft()); final NewLeft leftVal = binder.apply(oldSupplier.get()).getLeft(); @@ -137,7 +139,8 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL }; final Supplier<NewRight> rightSupp = () -> { - if(pairBound) return boundPair.getRight(); + if (pairBound) + return boundPair.getRight(); return binder.apply(oldSupplier.get()).getRight(); }; @@ -146,15 +149,18 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL } @Override - public <NewRightType> IPair<NewLeft, NewRightType> mapRight(final Function<NewRight, NewRightType> mapper) { + public <NewRightType> IPair<NewLeft, NewRightType> + mapRight(final Function<NewRight, NewRightType> mapper) { final Supplier<NewLeft> leftSupp = () -> { - if(pairBound) return boundPair.getLeft(); + if (pairBound) + return boundPair.getLeft(); return binder.apply(oldSupplier.get()).getLeft(); }; final Supplier<NewRightType> rightSupp = () -> { - if(pairBound) return mapper.apply(boundPair.getRight()); + if (pairBound) + return mapper.apply(boundPair.getRight()); final NewRight rightVal = binder.apply(oldSupplier.get()).getRight(); @@ -165,8 +171,9 @@ public class HalfBoundLazyPair<OldType, NewLeft, NewRight> implements IPair<NewL } @Override - public <MergedType> MergedType merge(final BiFunction<NewLeft, NewRight, MergedType> merger) { - if(!pairBound) { + public <MergedType> MergedType + merge(final BiFunction<NewLeft, NewRight, MergedType> merger) { + if (!pairBound) { boundPair = binder.apply(oldSupplier.get()); pairBound = true; diff --git a/src/main/java/bjc/data/internals/WrappedLazy.java b/src/main/java/bjc/data/internals/WrappedLazy.java index 17d2309..cda86fd 100644 --- a/src/main/java/bjc/data/internals/WrappedLazy.java +++ b/src/main/java/bjc/data/internals/WrappedLazy.java @@ -11,7 +11,7 @@ import bjc.data.Lazy; * * @author Ben Culkin * @param <ContainedType> - * The type of the wrapped value. + * The type of the wrapped value. */ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { /* Held value. */ @@ -21,19 +21,18 @@ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { * Create a new wrapped lazy value. * * @param wrappedHolder - * The holder to make lazy. + * The holder to make lazy. */ public WrappedLazy(final IHolder<ContainedType> wrappedHolder) { held = new Lazy<>(wrappedHolder); } /* - * This has an extra parameter, because otherwise it erases to the same - * as the public one. + * This has an extra parameter, because otherwise it erases to the same as the + * public one. * - * This is a case where reified generics would be useful, because then - * the compiler could know which one we meant without the dummy - * parameter. + * This is a case where reified generics would be useful, because then the + * compiler could know which one we meant without the dummy parameter. */ private WrappedLazy(final IHolder<IHolder<ContainedType>> wrappedHolder, @SuppressWarnings("unused") final boolean dummy) { @@ -41,8 +40,9 @@ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { } @Override - public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { - final IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { + public <BoundType> IHolder<BoundType> + bind(final Function<ContainedType, IHolder<BoundType>> binder) { + final IHolder<IHolder<BoundType>> newHolder = held.map(containedHolder -> { return containedHolder.bind(binder); }); @@ -50,15 +50,17 @@ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { - return (val) -> { + public <NewType> Function<ContainedType, IHolder<NewType>> + lift(final Function<ContainedType, NewType> func) { + return val -> { return new Lazy<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { - final IHolder<IHolder<MappedType>> newHolder = held.map((containedHolder) -> { + public <MappedType> IHolder<MappedType> + map(final Function<ContainedType, MappedType> mapper) { + final IHolder<IHolder<MappedType>> newHolder = held.map(containedHolder -> { return containedHolder.map(mapper); }); @@ -66,8 +68,9 @@ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { - held.transform((containedHolder) -> { + public IHolder<ContainedType> + transform(final UnaryOperator<ContainedType> transformer) { + held.transform(containedHolder -> { return containedHolder.transform(transformer); }); @@ -75,8 +78,9 @@ public class WrappedLazy<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { - return held.unwrap((containedHolder) -> { + public <UnwrappedType> UnwrappedType + unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { + return held.unwrap(containedHolder -> { return containedHolder.unwrap(unwrapper); }); } diff --git a/src/main/java/bjc/data/internals/WrappedOption.java b/src/main/java/bjc/data/internals/WrappedOption.java index eb4d120..6becc16 100644 --- a/src/main/java/bjc/data/internals/WrappedOption.java +++ b/src/main/java/bjc/data/internals/WrappedOption.java @@ -11,7 +11,7 @@ import bjc.data.Option; * * @author Ben Culkin. * @param <ContainedType> - * The wrapped type. + * The wrapped type. */ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { /* The held value. */ @@ -21,16 +21,15 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { * Create a new wrapped option. * * @param seedValue - * The value to wrap. + * The value to wrap. */ public WrappedOption(final IHolder<ContainedType> seedValue) { held = new Option<>(seedValue); } /* - * The dummy parameter is to ensure the compiler can pick the right - * method, because without this method erases to the same type as the - * public one. + * The dummy parameter is to ensure the compiler can pick the right method, + * because without this method erases to the same type as the public one. */ private WrappedOption(final IHolder<IHolder<ContainedType>> toHold, @SuppressWarnings("unused") final boolean dummy) { @@ -38,10 +37,12 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { } @Override - public <BoundType> IHolder<BoundType> bind(final Function<ContainedType, IHolder<BoundType>> binder) { - final IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { + public <BoundType> IHolder<BoundType> + bind(final Function<ContainedType, IHolder<BoundType>> binder) { + final IHolder<IHolder<BoundType>> newHolder = held.map(containedHolder -> { return containedHolder.bind((containedValue) -> { - if(containedValue == null) return new Option<>(null); + if (containedValue == null) + return new Option<>(null); return binder.apply(containedValue); }); @@ -51,17 +52,20 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift(final Function<ContainedType, NewType> func) { - return (val) -> { + public <NewType> Function<ContainedType, IHolder<NewType>> + lift(final Function<ContainedType, NewType> func) { + return val -> { return new Option<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map(final Function<ContainedType, MappedType> mapper) { - final IHolder<IHolder<MappedType>> newHolder = held.map((containedHolder) -> { + public <MappedType> IHolder<MappedType> + map(final Function<ContainedType, MappedType> mapper) { + final IHolder<IHolder<MappedType>> newHolder = held.map(containedHolder -> { return containedHolder.map((containedValue) -> { - if(containedValue == null) return null; + if (containedValue == null) + return null; return mapper.apply(containedValue); }); @@ -71,10 +75,12 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform(final UnaryOperator<ContainedType> transformer) { - held.transform((containedHolder) -> { + public IHolder<ContainedType> + transform(final UnaryOperator<ContainedType> transformer) { + held.transform(containedHolder -> { return containedHolder.transform((containedValue) -> { - if(containedValue == null) return null; + if (containedValue == null) + return null; return transformer.apply(containedValue); }); @@ -84,10 +90,12 @@ public class WrappedOption<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { - return held.unwrap((containedHolder) -> { + public <UnwrappedType> UnwrappedType + unwrap(final Function<ContainedType, UnwrappedType> unwrapper) { + return held.unwrap(containedHolder -> { return containedHolder.unwrap((containedValue) -> { - if(containedValue == null) return null; + if (containedValue == null) + return null; return unwrapper.apply(containedValue); }); diff --git a/src/main/java/bjc/esodata/AbbrevMap2.java b/src/main/java/bjc/esodata/AbbrevMap2.java index db41471..f131aec 100644 --- a/src/main/java/bjc/esodata/AbbrevMap2.java +++ b/src/main/java/bjc/esodata/AbbrevMap2.java @@ -3,19 +3,22 @@ package bjc.esodata; import java.util.*; /** - * A map that allows you to reference strings by unambiguous abbreviations to them. - * - * One example is that adding the string 'abc' would allow you to get it back with the following three keys + * A map that allows you to reference strings by unambiguous abbreviations to + * them. + * + * One example is that adding the string 'abc' would allow you to get it back + * with the following three keys * <ul> - * <li>a</li> - * <li>ab</li> - * <li>abc</li> + * <li>a</li> + * <li>ab</li> + * <li>abc</li> * </ul> * * @author Ben Culkin */ public class AbbrevMap2 { - // Stores a mapping from strings, to strings that they could be abbreviations for + // Stores a mapping from strings, to strings that they could be abbreviations + // for private Multimap<String, String> backing; /** @@ -29,7 +32,7 @@ public class AbbrevMap2 { * Add words to the map. * * @param words - * The words to add to the map. + * The words to add to the map. */ public void add(String... words) { for (String word : words) { @@ -58,7 +61,7 @@ public class AbbrevMap2 { * Remove words from the map. * * @param words - * The words to remove from the map. + * The words to remove from the map. */ public void removeWords(String... words) { for (String word : words) { @@ -72,7 +75,7 @@ public class AbbrevMap2 { * Get all of the strings that a string could be an abbreviation for. * * @param word - * The word to attempt to deabbreviate. + * The word to attempt to deabbreviate. * * @return All of the possible deabbreviations for that word. */ @@ -84,9 +87,10 @@ public class AbbrevMap2 { * Get the unambiguous thing the string is an abbreviation for. * * @param word - * The word to attempt to deabbreviate. + * The word to attempt to deabbreviate. * - * @return The unambiguous deabbreviation of the string, or null if there isn't one. + * @return The unambiguous deabbreviation of the string, or null if there isn't + * one. */ public String deabbrev(String word) { Set<String> st = backing.get(word); diff --git a/src/main/java/bjc/esodata/DefaultList.java b/src/main/java/bjc/esodata/DefaultList.java index e4b2806..c4535bd 100644 --- a/src/main/java/bjc/esodata/DefaultList.java +++ b/src/main/java/bjc/esodata/DefaultList.java @@ -9,17 +9,17 @@ import java.util.List; * * @author Ben Culkin * @param <ValueType> - * The type of the values contained in the list. + * The type of the values contained in the list. */ public class DefaultList<ValueType> extends AbstractList<ValueType> { /* * @NOTE 9/17/18 * - * A possible feature to add would be the ability to set a 'default - * index', so that the default value is 'whatever is at that list index' + * A possible feature to add would be the ability to set a 'default index', so + * that the default value is 'whatever is at that list index' * - * Of course, this would cause an exception if that index was out of - * bounds, but what are you going to do? + * Of course, this would cause an exception if that index was out of bounds, but + * what are you going to do? */ private ValueType defVal; @@ -35,9 +35,9 @@ public class DefaultList<ValueType> extends AbstractList<ValueType> { /** * Create a new DefaultList, with a set default value. - * + * * @param defVal - * The default value for the list. + * The default value for the list. */ public DefaultList(ValueType defVal) { this(new ArrayList<>(), defVal); @@ -45,10 +45,10 @@ public class DefaultList<ValueType> extends AbstractList<ValueType> { /** * Create a new DefaultList, with a specific backing list. - * + * * @param backer - * The backing list to use. - * + * The backing list to use. + * */ public DefaultList(List<ValueType> backer) { this(backer, null); @@ -56,12 +56,12 @@ public class DefaultList<ValueType> extends AbstractList<ValueType> { /** * Create a new DefaultList, with a set default value. - * + * * @param backer - * The backing list to use. - * + * The backing list to use. + * * @param defVal - * The default value for the list. + * The default value for the list. */ public DefaultList(List<ValueType> backer, ValueType defVal) { this.defVal = defVal; @@ -71,7 +71,7 @@ public class DefaultList<ValueType> extends AbstractList<ValueType> { /** * Get the default value. - * + * * @return The default value. */ public ValueType getDefault() { @@ -80,8 +80,9 @@ public class DefaultList<ValueType> extends AbstractList<ValueType> { /** * Set the default value. - * - * @param defVal The default value. + * + * @param defVal + * The default value. */ public void setDefault(ValueType defVal) { this.defVal = defVal; @@ -89,7 +90,8 @@ public class DefaultList<ValueType> extends AbstractList<ValueType> { @Override public ValueType get(int idx) { - if (idx < 0 || idx >= backing.size()) return defVal; + if (idx < 0 || idx >= backing.size()) + return defVal; return backing.get(idx); } diff --git a/src/main/java/bjc/esodata/Directory.java b/src/main/java/bjc/esodata/Directory.java index 4147e17..e083cd8 100644 --- a/src/main/java/bjc/esodata/Directory.java +++ b/src/main/java/bjc/esodata/Directory.java @@ -7,21 +7,21 @@ package bjc.esodata; * be able to ensure that they can't write outside of it. * * @param <K> - * The key type of the map. + * The key type of the map. * @param <V> - * The value type of the map. + * The value type of the map. */ public interface Directory<K, V> { /** * Retrieves a given sub-directory. * * @param key - * The key to retrieve the sub-directory for. + * The key to retrieve the sub-directory for. * * @return The sub-directory under that name. * * @throws IllegalArgumentException - * If the given sub-directory doesn't exist. + * If the given sub-directory doesn't exist. */ Directory<K, V> getSubdirectory(K key); @@ -29,7 +29,7 @@ public interface Directory<K, V> { * Check if a given sub-directory exists. * * @param key - * The key to look for the sub-directory under. + * The key to look for the sub-directory under. * * @return Whether or not a sub-directory of that name exists. */ @@ -39,9 +39,9 @@ public interface Directory<K, V> { * Insert a sub-directory into the dictionary. * * @param key - * The name of the new sub-directory + * The name of the new sub-directory * @param value - * The sub-directory to insert + * The sub-directory to insert * * @return The old sub-directory attached to this key, or null if such a * sub-directory didn't exist @@ -54,13 +54,13 @@ public interface Directory<K, V> { * Will fail if a sub-directory of that name already exists. * * @param key - * The name of the new sub-directory. + * The name of the new sub-directory. * - * @return The new sub-directory, or null if one by that name already - * exists. + * @return The new sub-directory, or null if one by that name already exists. */ default Directory<K, V> newSubdirectory(final K key) { - if(hasSubdirectory(key)) return null; + if (hasSubdirectory(key)) + return null; final Directory<K, V> dir = new SimpleDirectory<>(); @@ -73,7 +73,7 @@ public interface Directory<K, V> { * Check if the directory contains a data-item under the given key. * * @param key - * The key to check for. + * The key to check for. * * @return Whether or not there is a data item for the given key. */ @@ -83,12 +83,12 @@ public interface Directory<K, V> { * Retrieve a given data-item from the directory. * * @param key - * The key to retrieve data for. + * The key to retrieve data for. * * @return The value for the given key. * * @throws IllegalArgumentException - * If no value exists for the given key. + * If no value exists for the given key. */ V getKey(K key); @@ -96,10 +96,10 @@ public interface Directory<K, V> { * Insert a data-item into the directory. * * @param key - * The key to insert into. + * The key to insert into. * * @param val - * The value to insert. + * The value to insert. * * @return The old value of key, or null if such a value didn't exist. */ diff --git a/src/main/java/bjc/esodata/DoubleSided.java b/src/main/java/bjc/esodata/DoubleSided.java index 6ecbdcf..8ac6684 100644 --- a/src/main/java/bjc/esodata/DoubleSided.java +++ b/src/main/java/bjc/esodata/DoubleSided.java @@ -2,7 +2,7 @@ package bjc.esodata; /** * Interface for a double-sided object. - * + * * @author bjculkin * */ @@ -10,8 +10,7 @@ public interface DoubleSided { /** * Flips the object. * - * The active side becomes inactive, and the inactive side becomes - * active. + * The active side becomes inactive, and the inactive side becomes active. */ void flip(); diff --git a/src/main/java/bjc/esodata/DoubleTape.java b/src/main/java/bjc/esodata/DoubleTape.java index c36fcff..cc7cdb9 100644 --- a/src/main/java/bjc/esodata/DoubleTape.java +++ b/src/main/java/bjc/esodata/DoubleTape.java @@ -20,7 +20,7 @@ package bjc.esodata; * Flip refers to the entire tape for 'obvious' reasons. * * @param <T> - * The element type of the tape. + * The element type of the tape. * * @author bjculkin */ @@ -42,7 +42,8 @@ public class DoubleTape<T> implements Tape<T>, DoubleSided { * auto-extension policy. * * @param autoExtnd - * Whether or not to auto-extend the tape to the right w/ nulls. + * Whether or not to auto-extend the tape to the right w/ + * nulls. */ public DoubleTape(final boolean autoExtnd) { front = new SingleTape<>(autoExtnd); @@ -111,7 +112,7 @@ public class DoubleTape<T> implements Tape<T>, DoubleSided { public boolean left(final int amt) { final boolean succ = front.left(amt); - if(succ) { + if (succ) { back.right(amt); } @@ -127,13 +128,14 @@ public class DoubleTape<T> implements Tape<T>, DoubleSided { public boolean right(final int amt) { final boolean succ = front.right(amt); - if(succ) { + if (succ) { back.left(amt); } return succ; } + @Override public boolean seekTo(int tgtPos) { return front.seekTo(tgtPos); } @@ -165,19 +167,26 @@ public class DoubleTape<T> implements Tape<T>, DoubleSided { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof DoubleTape<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof DoubleTape<?>)) + return false; final DoubleTape<?> other = (DoubleTape<?>) obj; - if(back == null) { - if(other.back != null) return false; - } else if(!back.equals(other.back)) return false; - - if(front == null) { - if(other.front != null) return false; - } else if(!front.equals(other.front)) return false; + if (back == null) { + if (other.back != null) + return false; + } else if (!back.equals(other.back)) + return false; + + if (front == null) { + if (other.front != null) + return false; + } else if (!front.equals(other.front)) + return false; return true; } diff --git a/src/main/java/bjc/esodata/MapSet.java b/src/main/java/bjc/esodata/MapSet.java index cbb5d34..a80c482 100644 --- a/src/main/java/bjc/esodata/MapSet.java +++ b/src/main/java/bjc/esodata/MapSet.java @@ -8,13 +8,13 @@ import java.util.Set; /** * A string-keyed set of maps. - * + * * @author bjculkin * * @param <KeyType> - * The key type of the maps. + * The key type of the maps. * @param <ValueType> - * The value type of the maps. + * The value type of the maps. */ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> { private Map<String, Map<KeyType, ValueType>> backing; @@ -30,9 +30,9 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> /** * Create a new set of maps, with the specified set of maps. - * + * * @param back - * The set of maps to use. + * The set of maps to use. */ public MapSet(Map<String, Map<KeyType, ValueType>> back) { backing = back; @@ -40,11 +40,11 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> /** * Add a keyed map. - * + * * @param key - * The key for the map. + * The key for the map. * @param map - * The map itself. + * The map itself. */ public void addMap(String key, Map<KeyType, ValueType> map) { backing.put(key, map); @@ -61,9 +61,9 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> /** * Check if there is a map attached to the specified key. - * + * * @param key - * The key to look for. + * The key to look for. * @return Whether or not there is anything attached to the key. */ public boolean containsMap(String key) { @@ -72,9 +72,9 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> /** * Get the map attached to a specified key. - * + * * @param key - * The key to look for. + * The key to look for. * @return The map attached to the key. */ public Map<KeyType, ValueType> getMap(String key) { @@ -83,7 +83,7 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> /** * Get all of the backing entries. - * + * * @return The backing entries. */ public Set<Map.Entry<String, Map<KeyType, ValueType>>> getMapEntries() { @@ -92,7 +92,7 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> /** * Get all of the keys. - * + * * @return The keys currently in use. */ public Set<String> getMapKeys() { @@ -101,7 +101,7 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> /** * Get all of the keyed maps. - * + * * @return The keyed maps. */ public Collection<Map<KeyType, ValueType>> getMapValues() { @@ -110,13 +110,14 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> /** * Set the current map. - * + * * @param key - * The key to use as the current map. + * The key to use as the current map. * @return False if there is no map attached to the key, true otherwise. */ public boolean setMap(String key) { - if (!backing.containsKey(key)) return false; + if (!backing.containsKey(key)) + return false; currentMap = backing.get(key); @@ -124,11 +125,11 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> } /** - * Sets the current map, or creates a new one if there isn't one - * attached to that key. - * + * Sets the current map, or creates a new one if there isn't one attached to + * that key. + * * @param key - * The key to use as the current map. + * The key to use as the current map. */ public void setCreateMap(String key) { if (!backing.containsKey(key)) { @@ -144,11 +145,11 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> /** * Set the current map, or bind a map to it. - * + * * @param key - * The key to set or bind. + * The key to set or bind. * @param map - * The map to bind to the key if it isn't present. + * The map to bind to the key if it isn't present. */ public void setPutMap(String key, Map<KeyType, ValueType> map) { if (!backing.containsKey(key)) { @@ -164,14 +165,16 @@ public class MapSet<KeyType, ValueType> extends AbstractMap<KeyType, ValueType> @Override public Set<Map.Entry<KeyType, ValueType>> entrySet() { - if (currentMap == null) throw new NullPointerException("Current map is not set"); + if (currentMap == null) + throw new NullPointerException("Current map is not set"); return currentMap.entrySet(); } @Override public ValueType put(KeyType key, ValueType value) { - if (currentMap == null) throw new NullPointerException("Current map is not set"); + if (currentMap == null) + throw new NullPointerException("Current map is not set"); return currentMap.put(key, value); } diff --git a/src/main/java/bjc/esodata/Multimap.java b/src/main/java/bjc/esodata/Multimap.java index 5706db3..f0876db 100644 --- a/src/main/java/bjc/esodata/Multimap.java +++ b/src/main/java/bjc/esodata/Multimap.java @@ -5,9 +5,10 @@ import java.util.*; /** * A map that has support for multiple values for a given key. * - * Whenever you give another value for a key, that is then returned for that key. About the only - * somewhat complex thing, is that, if you add the same key-value pair multiple times, it will only - * show up once. However, you will have to remove that pair as many times as you added it. + * Whenever you give another value for a key, that is then returned for that + * key. About the only somewhat complex thing, is that, if you add the same + * key-value pair multiple times, it will only show up once. However, you will + * have to remove that pair as many times as you added it. * * @author Ben Culkin */ @@ -25,14 +26,14 @@ public class Multimap<KeyType, ValueType> { * Add a key-value mapping to the map. * * @param key - * The key to store the value under. + * The key to store the value under. * * @param value - * The value to store. + * The value to store. */ public void add(KeyType key, ValueType value) { - ThresholdSet<ValueType> container = backing.computeIfAbsent(key, - (k) -> new ThresholdSet<>()); + ThresholdSet<ValueType> container + = backing.computeIfAbsent(key, k -> new ThresholdSet<>()); container.add(value); } @@ -41,14 +42,15 @@ public class Multimap<KeyType, ValueType> { * Delete a particular key-value mapping from the map. * * @param key - * The key of the mapping to remove. + * The key of the mapping to remove. * * @param value - * The value of the mapping to remove. + * The value of the mapping to remove. */ public void remove(KeyType key, ValueType value) { // We have no values for that key; bail. - if (!backing.containsKey(key)) return; + if (!backing.containsKey(key)) + return; backing.get(key).remove(value); } @@ -57,7 +59,7 @@ public class Multimap<KeyType, ValueType> { * Delete all of the values associated with a particular key. * * @param key - * The key to remove values for. + * The key to remove values for. */ public void remove(KeyType key) { backing.remove(key); @@ -67,12 +69,13 @@ public class Multimap<KeyType, ValueType> { * Get a set containing all of the values that are recorded for that key. * * @param key - * The key to look up values for. + * The key to look up values for. * * @return A set containing all of the values that have been mapped to that key. */ public Set<ValueType> get(KeyType key) { - if (!backing.containsKey(key)) return new HashSet<>(); + if (!backing.containsKey(key)) + return new HashSet<>(); return backing.get(key).values(); } @@ -81,8 +84,8 @@ public class Multimap<KeyType, ValueType> { * Check if there is at least one value mapped to the given key. * * @param key - * The key to check for mappings for. - * + * The key to check for mappings for. + * * @return Whether or not there is at least one value mapped to the key. */ public boolean contains(KeyType key) { @@ -93,15 +96,17 @@ public class Multimap<KeyType, ValueType> { * Check if there is at least one instance of a particular key-value mapping. * * @param key - * The key to check for mappings for. + * The key to check for mappings for. * * @param value - * The value to check for mappings for. - * - * @return Whether or not there is at least one instance of the given key-value mapping. + * The value to check for mappings for. + * + * @return Whether or not there is at least one instance of the given key-value + * mapping. */ public boolean contains(KeyType key, ValueType value) { - if (!backing.containsKey(key)) return false; + if (!backing.containsKey(key)) + return false; return backing.get(key).contains(value) > 0; } diff --git a/src/main/java/bjc/esodata/PushdownMap.java b/src/main/java/bjc/esodata/PushdownMap.java index 5db5f05..54ae939 100644 --- a/src/main/java/bjc/esodata/PushdownMap.java +++ b/src/main/java/bjc/esodata/PushdownMap.java @@ -17,10 +17,10 @@ import bjc.funcdata.IMap; * @author EVE * * @param <KeyType> - * The key of the map. + * The key of the map. * * @param <ValueType> - * The values in the map. + * The values in the map. */ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { /* Our backing storage. */ @@ -84,16 +84,15 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> @Override public <V2> IMap<KeyType, V2> transform(final Function<ValueType, V2> transformer) { /* - * @NOTE Can and should we support this? More to the point, - * maybe this should be a map sub-type that does what it needs - * to? + * @NOTE Can and should we support this? More to the point, maybe this should be + * a map sub-type that does what it needs to? */ throw new UnsupportedOperationException("Cannot transform pushdown maps."); } @Override public ValueType put(final KeyType key, final ValueType val) { - if(backing.containsKey(key)) { + if (backing.containsKey(key)) { final Stack<ValueType> stk = backing.get(key); final ValueType vl = stk.top(); @@ -114,7 +113,7 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> public ValueType remove(final KeyType key) { final Stack<ValueType> stk = backing.get(key); - if(stk.size() > 1) { + if (stk.size() > 1) { return stk.pop(); } @@ -138,15 +137,20 @@ public class PushdownMap<KeyType, ValueType> implements IMap<KeyType, ValueType> @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof PushdownMap<?, ?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof PushdownMap<?, ?>)) + return false; final PushdownMap<?, ?> other = (PushdownMap<?, ?>) obj; - if(backing == null) { - if(other.backing != null) return false; - } else if(!backing.equals(other.backing)) return false; + if (backing == null) { + if (other.backing != null) + return false; + } else if (!backing.equals(other.backing)) + return false; return true; } diff --git a/src/main/java/bjc/esodata/QueueStack.java b/src/main/java/bjc/esodata/QueueStack.java index 55c6fc4..c40721a 100644 --- a/src/main/java/bjc/esodata/QueueStack.java +++ b/src/main/java/bjc/esodata/QueueStack.java @@ -5,11 +5,11 @@ import java.util.LinkedList; /** * A FIFO implementation of a stack. - * + * * Basically, a stack that actually acts like a queue. * * @param <T> - * The datatype stored in the stack. + * The datatype stored in the stack. * * @author Ben Culkin */ @@ -29,14 +29,16 @@ public class QueueStack<T> extends Stack<T> { @Override public T pop() { - if(backing.isEmpty()) throw new StackUnderflow(); + if (backing.isEmpty()) + throw new StackUnderflow(); return backing.remove(); } @Override public T top() { - if(backing.isEmpty()) throw new StackUnderflow(); + if (backing.isEmpty()) + throw new StackUnderflow(); return backing.peek(); } @@ -74,15 +76,20 @@ public class QueueStack<T> extends Stack<T> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof QueueStack<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof QueueStack<?>)) + return false; final QueueStack<?> other = (QueueStack<?>) obj; - if(backing == null) { - if(other.backing != null) return false; - } else if(!backing.equals(other.backing)) return false; + if (backing == null) { + if (other.backing != null) + return false; + } else if (!backing.equals(other.backing)) + return false; return true; } diff --git a/src/main/java/bjc/esodata/SimpleDirectory.java b/src/main/java/bjc/esodata/SimpleDirectory.java index 8ac19cf..672d92f 100644 --- a/src/main/java/bjc/esodata/SimpleDirectory.java +++ b/src/main/java/bjc/esodata/SimpleDirectory.java @@ -11,10 +11,10 @@ import bjc.funcdata.IMap; * @author EVE * * @param <K> - * The key type of the directory. + * The key type of the directory. * * @param <V> - * The value type of the directory. + * The value type of the directory. */ public class SimpleDirectory<K, V> implements Directory<K, V> { /* Our sub-directories. */ @@ -71,19 +71,26 @@ public class SimpleDirectory<K, V> implements Directory<K, V> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof SimpleDirectory<?, ?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof SimpleDirectory<?, ?>)) + return false; final SimpleDirectory<?, ?> other = (SimpleDirectory<?, ?>) obj; - if(children == null) { - if(other.children != null) return false; - } else if(!children.equals(other.children)) return false; - - if(data == null) { - if(other.data != null) return false; - } else if(!data.equals(other.data)) return false; + if (children == null) { + if (other.children != null) + return false; + } else if (!children.equals(other.children)) + return false; + + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; return true; } diff --git a/src/main/java/bjc/esodata/SimpleStack.java b/src/main/java/bjc/esodata/SimpleStack.java index dc6566c..b50521e 100644 --- a/src/main/java/bjc/esodata/SimpleStack.java +++ b/src/main/java/bjc/esodata/SimpleStack.java @@ -7,7 +7,7 @@ import java.util.LinkedList; * Simple implementation of a stack. * * @param <T> - * The datatype stored in the stack. + * The datatype stored in the stack. * * @author Ben Culkin */ @@ -27,14 +27,16 @@ public class SimpleStack<T> extends Stack<T> { @Override public T pop() { - if(backing.isEmpty()) throw new StackUnderflow(); + if (backing.isEmpty()) + throw new StackUnderflow(); return backing.pop(); } @Override public T top() { - if(backing.isEmpty()) throw new StackUnderflow(); + if (backing.isEmpty()) + throw new StackUnderflow(); return backing.peek(); } @@ -67,15 +69,20 @@ public class SimpleStack<T> extends Stack<T> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof SimpleStack<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof SimpleStack<?>)) + return false; final SimpleStack<?> other = (SimpleStack<?>) obj; - if(backing == null) { - if(other.backing != null) return false; - } else if(!backing.equals(other.backing)) return false; + if (backing == null) { + if (other.backing != null) + return false; + } else if (!backing.equals(other.backing)) + return false; return true; } diff --git a/src/main/java/bjc/esodata/SingleTape.java b/src/main/java/bjc/esodata/SingleTape.java index c2957a6..f6f87be 100644 --- a/src/main/java/bjc/esodata/SingleTape.java +++ b/src/main/java/bjc/esodata/SingleTape.java @@ -15,7 +15,7 @@ import java.util.ArrayList; * policy. * * @param <T> - * The element type of the tape. + * The element type of the tape. * * @author bjculkin */ @@ -28,11 +28,10 @@ public class SingleTape<T> implements Tape<T> { protected boolean autoExtend; /** - * Create a new tape with the specified contents that doesn't - * autoextend. - * + * Create a new tape with the specified contents that doesn't autoextend. + * * @param vals - * The values to put on the tape. + * The values to put on the tape. */ @SafeVarargs public SingleTape(T... vals) { @@ -40,7 +39,7 @@ public class SingleTape<T> implements Tape<T> { backing = new ArrayList<>(vals.length); - for(T val : vals) { + for (T val : vals) { backing.add(val); } } @@ -52,24 +51,24 @@ public class SingleTape<T> implements Tape<T> { /** * Create a new tape with values taken from an iterable. - * + * * @param itr - * The iterable to get values from. + * The iterable to get values from. */ public SingleTape(Iterable<T> itr) { this(false); - for(T itm : itr) { + for (T itm : itr) { backing.add(itm); } } /** - * Create a new empty tape that follows the specified auto-extension - * policy. + * Create a new empty tape that follows the specified auto-extension policy. * * @param autoExtnd - * Whether or not to auto-extend the tape to the right w/ nulls. + * Whether or not to auto-extend the tape to the right w/ + * nulls. */ public SingleTape(final boolean autoExtnd) { autoExtend = autoExtnd; @@ -79,7 +78,8 @@ public class SingleTape<T> implements Tape<T> { @Override public T item() { - if (pos < 0 || pos >= backing.size()) return null; + if (pos < 0 || pos >= backing.size()) + return null; return backing.get(pos); } @@ -106,7 +106,7 @@ public class SingleTape<T> implements Tape<T> { @Override public void insertAfter(final T itm) { - if(pos == backing.size() - 1) { + if (pos == backing.size() - 1) { backing.add(itm); } else { backing.add(pos + 1, itm); @@ -116,7 +116,7 @@ public class SingleTape<T> implements Tape<T> { @Override public T remove() { final T res = backing.remove(pos); - if(pos != 0) { + if (pos != 0) { pos -= 1; } return res; @@ -139,7 +139,8 @@ public class SingleTape<T> implements Tape<T> { @Override public boolean left(final int amt) { - if(pos - amt < 0) return false; + if (pos - amt < 0) + return false; pos -= amt; return true; @@ -152,25 +153,27 @@ public class SingleTape<T> implements Tape<T> { @Override public boolean right(final int amt) { - if(pos + amt > backing.size()) { - if(autoExtend) { - while(pos + amt >= backing.size() - 1) { + if (pos + amt > backing.size()) { + if (autoExtend) { + while (pos + amt >= backing.size() - 1) { backing.add(null); } - } else return false; + } else + return false; } pos += amt; return true; } + @Override public boolean seekTo(int tgtPos) { - if(tgtPos < 0) + if (tgtPos < 0) return false; - if(tgtPos >= backing.size() - 1) - if(autoExtend) - while(tgtPos >= backing.size() - 1) + if (tgtPos >= backing.size() - 1) + if (autoExtend) + while (tgtPos >= backing.size() - 1) backing.add(null); else return false; @@ -184,7 +187,7 @@ public class SingleTape<T> implements Tape<T> { public void append(T itm) { backing.add(itm); } - + @Override public int hashCode() { final int prime = 31; @@ -197,21 +200,27 @@ public class SingleTape<T> implements Tape<T> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof SingleTape<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof SingleTape<?>)) + return false; final SingleTape<?> other = (SingleTape<?>) obj; - if(backing == null) { - if(other.backing != null) return false; - } else if(!backing.equals(other.backing)) return false; + if (backing == null) { + if (other.backing != null) + return false; + } else if (!backing.equals(other.backing)) + return false; return true; } @Override public String toString() { - return String.format("SingleTape [backing=%s, pos=%s, autoExtend=%s]", backing, pos, autoExtend); + return String.format("SingleTape [backing=%s, pos=%s, autoExtend=%s]", backing, + pos, autoExtend); } } diff --git a/src/main/java/bjc/esodata/SpaghettiStack.java b/src/main/java/bjc/esodata/SpaghettiStack.java index 1b7af25..fc3e154 100644 --- a/src/main/java/bjc/esodata/SpaghettiStack.java +++ b/src/main/java/bjc/esodata/SpaghettiStack.java @@ -8,7 +8,7 @@ import java.util.stream.Stream; * parent stack. * * @param <T> - * The datatype stored in the stack. + * The datatype stored in the stack. * * @author Ben Culkin */ @@ -22,7 +22,7 @@ class SpaghettiStack<T> extends Stack<T> { * Create a new empty spaghetti stack, off of the specified parent. * * @param par - * The parent stack + * The parent stack */ public SpaghettiStack(final Stack<T> par) { backing = new SimpleStack<>(); @@ -37,14 +37,16 @@ class SpaghettiStack<T> extends Stack<T> { @Override public T pop() { - if(backing.isEmpty()) return parent.pop(); + if (backing.isEmpty()) + return parent.pop(); return backing.pop(); } @Override public T top() { - if(backing.isEmpty()) return parent.top(); + if (backing.isEmpty()) + return parent.top(); return backing.top(); } @@ -62,7 +64,9 @@ class SpaghettiStack<T> extends Stack<T> { @SuppressWarnings("unchecked") @Override public T[] toArray() { - return (T[]) Stream.concat(Arrays.stream(parent.toArray()), Arrays.stream(backing.toArray())).toArray(); + return (T[]) Stream + .concat(Arrays.stream(parent.toArray()), Arrays.stream(backing.toArray())) + .toArray(); } @Override @@ -78,19 +82,26 @@ class SpaghettiStack<T> extends Stack<T> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof SpaghettiStack<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof SpaghettiStack<?>)) + return false; final SpaghettiStack<?> other = (SpaghettiStack<?>) obj; - if(backing == null) { - if(other.backing != null) return false; - } else if(!backing.equals(other.backing)) return false; - - if(parent == null) { - if(other.parent != null) return false; - } else if(!parent.equals(other.parent)) return false; + if (backing == null) { + if (other.backing != null) + return false; + } else if (!backing.equals(other.backing)) + return false; + + if (parent == null) { + if (other.parent != null) + return false; + } else if (!parent.equals(other.parent)) + return false; return true; } diff --git a/src/main/java/bjc/esodata/Stack.java b/src/main/java/bjc/esodata/Stack.java index 31c92f1..f2e00e3 100644 --- a/src/main/java/bjc/esodata/Stack.java +++ b/src/main/java/bjc/esodata/Stack.java @@ -16,20 +16,20 @@ import java.util.function.*; * <h2>Stack underflow</h2> * <p> * NOTE: In general, using any operation that attempts to remove more data from - * the stack than exists will cause a {@link StackUnderflow} to be - * thrown. Check the size of the stack if you want to avoid this. + * the stack than exists will cause a {@link StackUnderflow} to be thrown. Check + * the size of the stack if you want to avoid this. * <p> * </p> * * @param <T> - * The datatype stored in the stack. + * The datatype stored in the stack. * * @author Ben Culkin */ public abstract class Stack<T> { /** - * The exception thrown when attempting to access an element from the - * stack that isn't there. + * The exception thrown when attempting to access an element from the stack that + * isn't there. * * @author EVE */ @@ -42,7 +42,7 @@ public abstract class Stack<T> { * Push an element onto the stack. * * @param elm - * The element to insert. + * The element to insert. */ public abstract void push(T elm); @@ -54,8 +54,7 @@ public abstract class Stack<T> { public abstract T pop(); /** - * Retrieve the top element of this stack without removing it from the - * stack. + * Retrieve the top element of this stack without removing it from the stack. * * @return The top element of this stack. */ @@ -94,7 +93,7 @@ public abstract class Stack<T> { * Push multiple elements onto the stack. * * @param elms - * The elements to insert. + * The elements to insert. */ public void pushAll(T... elms) { for (T elm : elms) { @@ -106,7 +105,7 @@ public abstract class Stack<T> { * Push multiple elements onto the stack. * * @param elms - * The elements to insert. + * The elements to insert. */ public void pushAll(List<T> elms) { for (T elm : elms) { @@ -118,7 +117,7 @@ public abstract class Stack<T> { * Pop n items off of the stack and return them. * * @param n - * The number of items to pop off of the stack. + * The number of items to pop off of the stack. * * @return A list of the popped items, in the order they were popped. */ @@ -136,7 +135,7 @@ public abstract class Stack<T> { * Pop n items off of the stack and return them. * * @param n - * The number of items to pop off of the stack. + * The number of items to pop off of the stack. * * @return A list of the popped items, in the reverse order they were popped. */ @@ -158,10 +157,10 @@ public abstract class Stack<T> { * Drop n items from the stack. * * @param n - * The number of items to drop. + * The number of items to drop. */ public void drop(final int n) { - for(int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) { pop(); } } @@ -175,7 +174,7 @@ public abstract class Stack<T> { * Delete n items below the current one. * * @param n - * The number of items below the top to delete. + * The number of items below the top to delete. */ public void nip(final int n) { final T elm = pop(); @@ -194,15 +193,15 @@ public abstract class Stack<T> { * Replicate the top n items of the stack m times. * * @param n - * The number of items to duplicate. + * The number of items to duplicate. * * @param m - * The number of times to duplicate items. + * The number of times to duplicate items. */ public void multidup(final int n, final int m) { List<T> lst = multipoprev(n); - for(int i = 0; i <= m; i++) { + for (int i = 0; i <= m; i++) { pushAll(lst); } } @@ -211,7 +210,7 @@ public abstract class Stack<T> { * Duplicate the top n items of the stack. * * @param n - * The number of items to duplicate. + * The number of items to duplicate. */ public void dup(final int n) { multidup(n, 1); @@ -226,23 +225,23 @@ public abstract class Stack<T> { * Replicate the n elements below the top one m times. * * @param n - * The number of items to duplicate. + * The number of items to duplicate. * * @param m - * The number of times to duplicate items. + * The number of times to duplicate items. */ public void multiover(final int n, final int m) { T elm = pop(); List<T> lst = multipoprev(n); - for(final T nelm : lst) { + for (final T nelm : lst) { push(nelm); } push(elm); - for(int i = 0; i < m; i++) { + for (int i = 0; i < m; i++) { pushAll(lst); } } @@ -251,7 +250,7 @@ public abstract class Stack<T> { * Duplicate the n elements below the top one. * * @param n - * The number of items to duplicate. + * The number of items to duplicate. */ public void over(final int n) { multiover(n, 1); @@ -278,12 +277,12 @@ public abstract class Stack<T> { * Rotate the n items m deep on the stack i positions. * * @param n - * The number of items to rotate. + * The number of items to rotate. * @param m - * The number of positions the item is down in the stack. + * The number of positions the item is down in the stack. * @param i - * The number of steps to rotate. Pass a negative number to rotate things in the opposite - * direction. + * The number of steps to rotate. Pass a negative number to rotate + * things in the opposite direction. */ public void deepmultirot(int n, int m, int i) { List<T> kep = multipoprev(m); @@ -300,10 +299,10 @@ public abstract class Stack<T> { * Rotate the n items on top of the stack i positions. * * @param n - * The number of items to rotate. + * The number of items to rotate. * @param i - * The number of steps to rotate. Pass a negative number to rotate things in the opposite - * direction. + * The number of steps to rotate. Pass a negative number to rotate + * things in the opposite direction. */ public void multirot(int n, int i) { deepmultirot(n, 0, i); @@ -329,8 +328,8 @@ public abstract class Stack<T> { deepmultirot(2, 1, 1); } - /** - * Rotate the top three items on the stack + /** + * Rotate the top three items on the stack */ public void rot() { final T z = pop(); @@ -361,10 +360,10 @@ public abstract class Stack<T> { * Hides the top n elements on the stack from an action. * * @param n - * The number of elements to hide. + * The number of elements to hide. * * @param action - * The action to hide the elements from + * The action to hide the elements from */ public void dip(final int n, final Consumer<Stack<T>> action) { List<T> elms = multipoprev(n); @@ -378,21 +377,20 @@ public abstract class Stack<T> { * Hide the top element of the stack from an action. * * @param action - * The action to hide the top from + * The action to hide the top from */ public void dip(final Consumer<Stack<T>> action) { dip(1, action); } /** - * Copy the top n elements on the stack, replacing them once an action - * is done. + * Copy the top n elements on the stack, replacing them once an action is done. * * @param n - * The number of elements to copy. + * The number of elements to copy. * * @param action - * The action to execute. + * The action to execute. */ public void keep(final int n, final Consumer<Stack<T>> action) { dup(n); @@ -401,11 +399,10 @@ public abstract class Stack<T> { } /** - * Copy the first element on the stack, replacing them once an action - * is done. + * Copy the first element on the stack, replacing them once an action is done. * * @param action - * The action to execute. + * The action to execute. */ public void keep(final Consumer<Stack<T>> action) { keep(1, action); @@ -415,15 +412,15 @@ public abstract class Stack<T> { * Apply all the actions in a list to the top n elements of the stack. * * @param n - * The number of elements to give to cons. + * The number of elements to give to cons. * * @param actions - * The actions to execute. + * The actions to execute. */ public void multicleave(final int n, final List<Consumer<Stack<T>>> actions) { List<T> elms = multipoprev(n); - for(final Consumer<Stack<T>> action : actions) { + for (final Consumer<Stack<T>> action : actions) { pushAll(elms); action.accept(this); @@ -434,15 +431,15 @@ public abstract class Stack<T> { * Apply all the actions in a list to the top n elements of the stack. * * @param n - * The number of elements to give to cons. + * The number of elements to give to cons. * * @param actions - * The actions to execute. + * The actions to execute. */ public void multicleave(final int n, final Consumer<Stack<T>>... actions) { List<T> elms = multipoprev(n); - for(final Consumer<Stack<T>> action : actions) { + for (final Consumer<Stack<T>> action : actions) { pushAll(elms); action.accept(this); @@ -453,7 +450,7 @@ public abstract class Stack<T> { * Apply all the actions in a list to the top element of the stack. * * @param actions - * The actions to execute. + * The actions to execute. */ public void cleave(final List<Consumer<Stack<T>>> actions) { multicleave(1, actions); @@ -463,7 +460,7 @@ public abstract class Stack<T> { * Apply all the actions in a list to the top element of the stack. * * @param actions - * The actions to execute. + * The actions to execute. */ public void cleave(final Consumer<Stack<T>>... actions) { multicleave(1, actions); @@ -473,10 +470,10 @@ public abstract class Stack<T> { * Apply every action in a list of actions to n arguments. * * @param n - * The number of parameters each action takes. + * The number of parameters each action takes. * * @param actions - * The actions to execute. + * The actions to execute. */ public void multispread(final int n, final List<Consumer<Stack<T>>> actions) { List<List<T>> nelms = new LinkedList<>(); @@ -488,7 +485,7 @@ public abstract class Stack<T> { } Iterator<Consumer<Stack<T>>> itr = actions.iterator(); - for(final List<T> elms : nelms) { + for (final List<T> elms : nelms) { pushAll(elms); itr.next().accept(this); @@ -499,10 +496,10 @@ public abstract class Stack<T> { * Apply every action in a list of actions to n arguments. * * @param n - * The number of parameters each action takes. + * The number of parameters each action takes. * * @param actions - * The actions to execute. + * The actions to execute. */ public void multispread(final int n, final Consumer<Stack<T>>... actions) { List<List<T>> nelms = new LinkedList<>(); @@ -514,7 +511,7 @@ public abstract class Stack<T> { } int i = 0; - for(final List<T> elms : nelms) { + for (final List<T> elms : nelms) { pushAll(elms); actions[i++].accept(this); @@ -522,22 +519,22 @@ public abstract class Stack<T> { } /** - * Apply the actions in a list of actions to corresponding elements from - * the stack. + * Apply the actions in a list of actions to corresponding elements from the + * stack. * * @param conses - * The actions to execute. + * The actions to execute. */ public void spread(final List<Consumer<Stack<T>>> conses) { multispread(1, conses); } /** - * Apply the actions in a list of actions to corresponding elements from - * the stack. + * Apply the actions in a list of actions to corresponding elements from the + * stack. * * @param conses - * The actions to execute. + * The actions to execute. */ public void spread(final Consumer<Stack<T>>... conses) { multispread(1, conses); @@ -547,18 +544,18 @@ public abstract class Stack<T> { * Apply an action to the first m groups of n arguments. * * @param n - * The number of arguments cons takes. + * The number of arguments cons takes. * * @param m - * The number of time to call cons. + * The number of time to call cons. * * @param action - * The action to execute. + * The action to execute. */ public void multiapply(final int n, final int m, final Consumer<Stack<T>> action) { final List<Consumer<Stack<T>>> actions = new ArrayList<>(m); - for(int i = 0; i < m; i++) { + for (int i = 0; i < m; i++) { actions.add(action); } @@ -569,10 +566,10 @@ public abstract class Stack<T> { * Apply an action n times to the corresponding elements in the stack. * * @param n - * The number of times to execute cons. + * The number of times to execute cons. * * @param action - * The action to execute. + * The action to execute. */ public void apply(final int n, final Consumer<Stack<T>> action) { multiapply(1, n, action); diff --git a/src/main/java/bjc/esodata/Tape.java b/src/main/java/bjc/esodata/Tape.java index 7d5fd9a..134ba62 100644 --- a/src/main/java/bjc/esodata/Tape.java +++ b/src/main/java/bjc/esodata/Tape.java @@ -8,7 +8,7 @@ package bjc.esodata; * unbounded to the right, but in practice bounded by available memory. * * @param <T> - * The element type of the tape. + * The element type of the tape. * * @author bjculkin */ @@ -24,7 +24,7 @@ public interface Tape<T> { * Set the item the tape is currently on. * * @param itm - * The new value for the tape item. + * The new value for the tape item. */ void item(T itm); @@ -46,7 +46,7 @@ public interface Tape<T> { * Insert an element before the current item. * * @param itm - * The item to add. + * The item to add. */ void insertBefore(T itm); @@ -54,7 +54,7 @@ public interface Tape<T> { * Insert an element after the current item. * * @param itm - * The item to insert. + * The item to insert. */ void insertAfter(T itm); @@ -86,11 +86,11 @@ public interface Tape<T> { /** * Move the cursor the specified amount left. * - * The cursor can't go past zero. Attempts to move the cursor by amounts - * that would exceed zero don't move the cursor at all. + * The cursor can't go past zero. Attempts to move the cursor by amounts that + * would exceed zero don't move the cursor at all. * * @param amt - * The amount to attempt to move the cursor left. + * The amount to attempt to move the cursor left. * * @return True if the cursor was moved left. */ @@ -107,7 +107,7 @@ public interface Tape<T> { * Move the cursor the specified amount right. * * @param amt - * The amount to move the cursor right by. + * The amount to move the cursor right by. * * @return Whether the cursor was moved right. */ @@ -115,37 +115,40 @@ public interface Tape<T> { /** * Seek to an absolute position on the tape. - * + * * @param pos - * The position to seek to. + * The position to seek to. * @return Whether or not the tape successfully seeked to that position. */ boolean seekTo(int pos); /** * Check if this tape is at its end. - * + * * Equivalent to checking if position() == size(). - * + * * @return Whether or not the tape is at its end. */ default boolean atEnd() { return position() == size(); } - + /** * Append an item to the tape. + * + * By default, uses a fairly non-performant implementation. Should be overidden + * in subclasses to be more performant. * - * By default, uses a fairly non-performant implementation. Should be overidden in subclasses to be more performant. - * @param itm The item to append. + * @param itm + * The item to append. */ default void append(T itm) { int pos = position(); - + last(); - + insertAfter(itm); - + seekTo(pos); } } diff --git a/src/main/java/bjc/esodata/ThresholdSet.java b/src/main/java/bjc/esodata/ThresholdSet.java index 6076a2a..50d95d0 100644 --- a/src/main/java/bjc/esodata/ThresholdSet.java +++ b/src/main/java/bjc/esodata/ThresholdSet.java @@ -7,16 +7,18 @@ import java.util.*; * * More specifically, this is a set/map combo type. * - * Initially, when you add an item, it will go into the set. Attempting to add a duplicate item to - * that set will cause the entry to be removed from the set, and added to the map, which will count - * the number of times that particular item has been added to the set. If you remove enough copies - * of that item to put it back down to 1 copy, that copy will be removed from the map, and readded - * to the set. + * Initially, when you add an item, it will go into the set. Attempting to add a + * duplicate item to that set will cause the entry to be removed from the set, + * and added to the map, which will count the number of times that particular + * item has been added to the set. If you remove enough copies of that item to + * put it back down to 1 copy, that copy will be removed from the map, and + * readded to the set. * - * The iterator that this type gives by default is an iterator over all of the values in the set, - * not including any of those in the map. + * The iterator that this type gives by default is an iterator over all of the + * values in the set, not including any of those in the map. * - * @param <KeyType> The value being counted. + * @param <KeyType> + * The value being counted. * * @author Ben Culkin */ @@ -24,30 +26,33 @@ public class ThresholdSet<KeyType> { // View of this class as a java.util.Set private class SetView extends AbstractSet<KeyType> { /* - * This is technically not a valid implementation of add, because it does not guarantee that - * the set will contain key after it returns (as a matter of fact, attempting to add the - * component might actually cause it to be removed from the collection). + * This is technically not a valid implementation of add, because it does not + * guarantee that the set will contain key after it returns (as a matter of + * fact, attempting to add the component might actually cause it to be removed + * from the collection). */ @Override public boolean add(KeyType key) { // Qualified-this; allows us to reference the 'this' of our enclosing type. int ret = ThresholdSet.this.add(key); - + // No change to set contents - if (ret > 2) return false; + if (ret > 2) + return false; return true; } - + @Override public boolean remove(Object o) { // Will throw a ClassCastException if you give us something bad. - KeyType k = (KeyType)o; + KeyType k = (KeyType) o; int ret = ThresholdSet.this.remove(k); // We removed the element. - if (ret == 0) return true; + if (ret == 0) + return true; return false; } @@ -55,12 +60,13 @@ public class ThresholdSet<KeyType> { @Override public boolean contains(Object o) { // Will throw a ClassCastException if you give us something bad. - KeyType k = (KeyType)o; + KeyType k = (KeyType) o; int ret = ThresholdSet.this.contains(k); // The object is set-visible - if (ret == 1) return true; + if (ret == 1) + return true; return false; } @@ -80,7 +86,8 @@ public class ThresholdSet<KeyType> { private Set<KeyType> keySet; // @TODO :CountMap Ben Culkin 6/19/2019 - // Replace this with a CountSet or some equivalent concept, whenever that gets written, if that + // Replace this with a CountSet or some equivalent concept, whenever that gets + // written, if that // gets written private Map<KeyType, Integer> keyMap; @@ -95,8 +102,8 @@ public class ThresholdSet<KeyType> { /** * Add multiple keys at once to the map. * - * @param keys - * The keys to add. + * @param keys + * The keys to add. * * @return An array containing the results of adding the keys. */ @@ -114,9 +121,10 @@ public class ThresholdSet<KeyType> { * Add a key to the collection. * * @param key - * The key to add to the collection. + * The key to add to the collection. * - * @return The number of times that key now exists in the collection. Should always be < 0. + * @return The number of times that key now exists in the collection. Should + * always be < 0. */ public int add(KeyType key) { if (keySet.contains(key)) { @@ -145,7 +153,7 @@ public class ThresholdSet<KeyType> { * Remove a bunch of keys from the collection. * * @param keys - * The keys to remove from the collection. + * The keys to remove from the collection. * * @return The results from removing the keys. */ @@ -163,10 +171,10 @@ public class ThresholdSet<KeyType> { * Remove a key from the collection. * * @param key - * The key to remove from the collection. + * The key to remove from the collection. * - * @return The number of times that key now exists in the collection. Returns -1 if that key - * wasn't in the collection beforehand. + * @return The number of times that key now exists in the collection. Returns -1 + * if that key wasn't in the collection beforehand. */ public int remove(KeyType key) { if (keySet.contains(key)) { @@ -200,7 +208,7 @@ public class ThresholdSet<KeyType> { * Get the number of times the set contains a set of given keys. * * @param keys - * The keys to look for. + * The keys to look for. * * @return The containment counts for each key. */ @@ -218,13 +226,15 @@ public class ThresholdSet<KeyType> { * Get the number of times the set contains a given key. * * @param key - * The key to look for. + * The key to look for. * * @return The number of times the key occurs; -1 if it doesn't occur. */ public int contains(KeyType key) { - if (keySet.contains(key)) return 1; - if (!keyMap.containsKey(key)) return -1; + if (keySet.contains(key)) + return 1; + if (!keyMap.containsKey(key)) + return -1; return keyMap.get(key); } @@ -256,7 +266,7 @@ public class ThresholdSet<KeyType> { * Static threshold set constructor. * * @param keys - * The initial keys to add to the threshold set. + * The initial keys to add to the threshold set. */ @SafeVarargs public static <KType> ThresholdSet<KType> TS(KType... keys) { diff --git a/src/main/java/bjc/esodata/UnifiedDirectory.java b/src/main/java/bjc/esodata/UnifiedDirectory.java index dec940f..2221615 100644 --- a/src/main/java/bjc/esodata/UnifiedDirectory.java +++ b/src/main/java/bjc/esodata/UnifiedDirectory.java @@ -11,10 +11,10 @@ import bjc.funcdata.IMap; * @author EVE * * @param <K> - * The key type of the directory. + * The key type of the directory. * * @param <V> - * The value type of the directory. + * The value type of the directory. */ public class UnifiedDirectory<K, V> implements Directory<K, V> { /* Our directory children. */ @@ -40,7 +40,7 @@ public class UnifiedDirectory<K, V> implements Directory<K, V> { @Override public Directory<K, V> putSubdirectory(final K key, final Directory<K, V> val) { - if(data.containsKey(key)) { + if (data.containsKey(key)) { final String msg = String.format("Key %s is already used for data", key); throw new IllegalArgumentException(msg); @@ -61,8 +61,9 @@ public class UnifiedDirectory<K, V> implements Directory<K, V> { @Override public V putKey(final K key, final V val) { - if(children.containsKey(key)) { - final String msg = String.format("Key %s is already used for sub-directories.", key); + if (children.containsKey(key)) { + final String msg + = String.format("Key %s is already used for sub-directories.", key); throw new IllegalArgumentException(msg); } @@ -81,19 +82,26 @@ public class UnifiedDirectory<K, V> implements Directory<K, V> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof UnifiedDirectory<?, ?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof UnifiedDirectory<?, ?>)) + return false; final UnifiedDirectory<?, ?> other = (UnifiedDirectory<?, ?>) obj; - if(children == null) { - if(other.children != null) return false; - } else if(!children.equals(other.children)) return false; - - if(data == null) { - if(other.data != null) return false; - } else if(!data.equals(other.data)) return false; + if (children == null) { + if (other.children != null) + return false; + } else if (!children.equals(other.children)) + return false; + + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; return true; } diff --git a/src/main/java/bjc/funcdata/ExtendedMap.java b/src/main/java/bjc/funcdata/ExtendedMap.java index 76fac01..bd500f4 100644 --- a/src/main/java/bjc/funcdata/ExtendedMap.java +++ b/src/main/java/bjc/funcdata/ExtendedMap.java @@ -11,10 +11,10 @@ import java.util.function.Function; * @author Ben Culkin * * @param <KeyType> - * The type of the keys of the map. + * The type of the keys of the map. * * @param <ValueType> - * The type of the values of the map. + * The type of the values of the map. */ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { /* The map we delegate lookups to. */ @@ -26,12 +26,13 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { * Create a new extended map. * * @param delegate - * The map to lookup things in. - * + * The map to lookup things in. + * * @param store - * The map to store things in. + * The map to store things in. */ - public ExtendedMap(final IMap<KeyType, ValueType> delegate, final IMap<KeyType, ValueType> store) { + public ExtendedMap(final IMap<KeyType, ValueType> delegate, + final IMap<KeyType, ValueType> store) { this.delegate = delegate; this.store = store; } @@ -43,7 +44,8 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { @Override public boolean containsKey(final KeyType key) { - if(store.containsKey(key)) return true; + if (store.containsKey(key)) + return true; return delegate.containsKey(key); } @@ -76,7 +78,8 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { @Override public ValueType get(final KeyType key) { - if(store.containsKey(key)) return store.get(key); + if (store.containsKey(key)) + return store.get(key); return delegate.get(key); } @@ -97,7 +100,8 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { } @Override - public <MappedValue> IMap<KeyType, MappedValue> transform(final Function<ValueType, MappedValue> transformer) { + public <MappedValue> IMap<KeyType, MappedValue> + transform(final Function<ValueType, MappedValue> transformer) { return new TransformedValueMap<>(this, transformer); } @@ -108,7 +112,8 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { @Override public ValueType remove(final KeyType key) { - if(!store.containsKey(key)) return delegate.remove(key); + if (!store.containsKey(key)) + return delegate.remove(key); return store.remove(key); } @@ -134,18 +139,25 @@ class ExtendedMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof ExtendedMap)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof ExtendedMap)) + return false; final ExtendedMap<?, ?> other = (ExtendedMap<?, ?>) obj; - if(delegate == null) { - if(other.delegate != null) return false; - } else if(!delegate.equals(other.delegate)) return false; - if(store == null) { - if(other.store != null) return false; - } else if(!store.equals(other.store)) return false; + if (delegate == null) { + if (other.delegate != null) + return false; + } else if (!delegate.equals(other.delegate)) + return false; + if (store == null) { + if (other.store != null) + return false; + } else if (!store.equals(other.store)) + return false; return true; } diff --git a/src/main/java/bjc/funcdata/FunctionalList.java b/src/main/java/bjc/funcdata/FunctionalList.java index 99b36fe..2cdfa27 100644 --- a/src/main/java/bjc/funcdata/FunctionalList.java +++ b/src/main/java/bjc/funcdata/FunctionalList.java @@ -27,7 +27,7 @@ import bjc.data.Pair; * @author ben * * @param <E> - * The type in this list + * The type in this list */ public class FunctionalList<E> implements Cloneable, IList<E> { /* The list used as a backing store */ @@ -44,35 +44,36 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * Takes O(n) time, where n is the number of items specified * * @param items - * The items to put into this functional list. + * The items to put into this functional list. */ @SafeVarargs public FunctionalList(final E... items) { wrapped = new ArrayList<>(items.length); - for(final E item : items) { + for (final E item : items) { wrapped.add(item); } } - + /** * Create a new functional list containing the specified items. * * Takes O(n) time, where n is the number of items specified * * @param items - * The items to put into this functional list. + * The items to put into this functional list. * @return The returned list. */ @SafeVarargs public static <T> IList<T> listOf(final T... items) { return new FunctionalList<>(items); } + /** * Create a new functional list with the specified size. * * @param size - * The size of the backing list . + * The size of the backing list . */ private FunctionalList(final int size) { wrapped = new ArrayList<>(size); @@ -84,10 +85,11 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * Takes O(1) time, since it doesn't copy the list. * * @param backing - * The list to use as a backing list. + * The list to use as a backing list. */ public FunctionalList(final List<E> backing) { - if(backing == null) throw new NullPointerException("Backing list must be non-null"); + if (backing == null) + throw new NullPointerException("Backing list must be non-null"); wrapped = backing; } @@ -99,10 +101,11 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public boolean allMatch(final Predicate<E> predicate) { - if(predicate == null) throw new NullPointerException("Predicate must be non-null"); + if (predicate == null) + throw new NullPointerException("Predicate must be non-null"); - for(final E item : wrapped) { - if(!predicate.test(item)) + for (final E item : wrapped) { + if (!predicate.test(item)) /* We've found a non-matching item. */ return false; } @@ -113,10 +116,11 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public boolean anyMatch(final Predicate<E> predicate) { - if(predicate == null) throw new NullPointerException("Predicate must be not null"); + if (predicate == null) + throw new NullPointerException("Predicate must be not null"); - for(final E item : wrapped) { - if(predicate.test(item)) + for (final E item : wrapped) { + if (predicate.test(item)) /* We've found a matching item. */ return true; } @@ -136,7 +140,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { public IList<E> clone() { final IList<E> cloned = new FunctionalList<>(); - for(final E element : wrapped) { + for (final E element : wrapped) { cloned.add(element); } @@ -144,10 +148,11 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public <T, F> IList<F> combineWith(final IList<T> rightList, final BiFunction<E, T, F> itemCombiner) { - if(rightList == null) { + public <T, F> IList<F> combineWith(final IList<T> rightList, + final BiFunction<E, T, F> itemCombiner) { + if (rightList == null) { throw new NullPointerException("Target combine list must not be null"); - } else if(itemCombiner == null) { + } else if (itemCombiner == null) { throw new NullPointerException("Combiner must not be null"); } @@ -156,8 +161,8 @@ public class FunctionalList<E> implements Cloneable, IList<E> { /* Get the iterator for the other list. */ final Iterator<T> rightIterator = rightList.toIterable().iterator(); - for(final Iterator<E> leftIterator = wrapped.iterator(); leftIterator.hasNext() - && rightIterator.hasNext();) { + for (final Iterator<E> leftIterator = wrapped.iterator(); + leftIterator.hasNext() && rightIterator.hasNext();) { /* Add the transformed items to the result list. */ final E leftVal = leftIterator.next(); final T rightVal = rightIterator.next(); @@ -176,21 +181,27 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public E first() { - if(wrapped.size() < 1) throw new NoSuchElementException("Attempted to get first element of empty list"); + if (wrapped.size() < 1) + throw new NoSuchElementException( + "Attempted to get first element of empty list"); return wrapped.get(0); } @Override public E last() { - if(wrapped.size() < 1) throw new NoSuchElementException("Attempted to get last element of empty list"); + if (wrapped.size() < 1) + throw new NoSuchElementException( + "Attempted to get last element of empty list"); return wrapped.get(wrapped.size() - 1); } @Override public E popFirst() { - if(wrapped.size() < 1) throw new NoSuchElementException("Attempted to pop first element of empty list"); + if (wrapped.size() < 1) + throw new NoSuchElementException( + "Attempted to pop first element of empty list"); E head = first(); wrapped.remove(0); @@ -200,7 +211,9 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public E popLast() { - if(wrapped.size() < 1) throw new NoSuchElementException("Attempted to pop last element of empty list"); + if (wrapped.size() < 1) + throw new NoSuchElementException( + "Attempted to pop last element of empty list"); E tail = last(); wrapped.remove(wrapped.size() - 1); @@ -210,14 +223,16 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public <T> IList<T> flatMap(final Function<E, IList<T>> expander) { - if(expander == null) throw new NullPointerException("Expander must not be null"); + if (expander == null) + throw new NullPointerException("Expander must not be null"); final IList<T> returned = new FunctionalList<>(this.wrapped.size()); forEach(element -> { final IList<T> expandedElement = expander.apply(element); - if(expandedElement == null) throw new NullPointerException("Expander returned null list"); + if (expandedElement == null) + throw new NullPointerException("Expander returned null list"); /* Add each element to the returned list. */ expandedElement.forEach(returned::add); @@ -228,22 +243,23 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public void forEach(final Consumer<? super E> action) { - if(action == null) throw new NullPointerException("Action is null"); + if (action == null) + throw new NullPointerException("Action is null"); wrapped.forEach(action); } @Override public void forEachIndexed(final BiConsumer<Integer, E> indexedAction) { - if(indexedAction == null) throw new NullPointerException("Action must not be null"); + if (indexedAction == null) + throw new NullPointerException("Action must not be null"); /* - * This is held b/c ref'd variables must be final/effectively - * final. + * This is held b/c ref'd variables must be final/effectively final. */ final IHolder<Integer> currentIndex = new Identity<>(0); - wrapped.forEach((element) -> { + wrapped.forEach(element -> { /* Call the action with the index and the value. */ indexedAction.accept(currentIndex.unwrap(index -> index), element); @@ -268,15 +284,15 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public IList<E> getMatching(final Predicate<E> predicate) { - if(predicate == null) throw new NullPointerException("Predicate must not be null"); + if (predicate == null) + throw new NullPointerException("Predicate must not be null"); final IList<E> returned = new FunctionalList<>(); - wrapped.forEach((element) -> { - if(predicate.test(element)) { + wrapped.forEach(element -> { + if (predicate.test(element)) { /* - * The item matches, so add it to the returned - * list. + * The item matches, so add it to the returned list. */ returned.add(element); } @@ -296,13 +312,16 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } /* Check if a partition has room for another item. */ - private Boolean isPartitionFull(final int numberPerPartition, final IHolder<IList<E>> currentPartition) { - return currentPartition.unwrap((partition) -> partition.getSize() >= numberPerPartition); + private Boolean isPartitionFull(final int numberPerPartition, + final IHolder<IList<E>> currentPartition) { + return currentPartition + .unwrap(partition -> partition.getSize() >= numberPerPartition); } @Override public <T> IList<T> map(final Function<E, T> elementTransformer) { - if(elementTransformer == null) throw new NullPointerException("Transformer must be not null"); + if (elementTransformer == null) + throw new NullPointerException("Transformer must be not null"); final IList<T> returned = new FunctionalList<>(this.wrapped.size()); @@ -321,8 +340,9 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public IList<IList<E>> partition(final int numberPerPartition) { - if(numberPerPartition < 1 || numberPerPartition > wrapped.size()) { - final String fmt = "%s is an invalid partition size. Must be between 1 and %d"; + if (numberPerPartition < 1 || numberPerPartition > wrapped.size()) { + final String fmt + = "%s is an invalid partition size. Must be between 1 and %d"; final String msg = String.format(fmt, numberPerPartition, wrapped.size()); throw new IllegalArgumentException(msg); @@ -334,7 +354,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { final IHolder<IList<E>> currentPartition = new Identity<>(new FunctionalList<>()); this.forEach(element -> { - if(isPartitionFull(numberPerPartition, currentPartition)) { + if (isPartitionFull(numberPerPartition, currentPartition)) { /* Add the partition to the list. */ returned.add(currentPartition.unwrap(partition -> partition)); @@ -356,7 +376,8 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public E randItem(final Function<Integer, Integer> rnd) { - if(rnd == null) throw new NullPointerException("Random source must not be null"); + if (rnd == null) + throw new NullPointerException("Random source must not be null"); final int randomIndex = rnd.apply(wrapped.size()); @@ -364,11 +385,12 @@ public class FunctionalList<E> implements Cloneable, IList<E> { } @Override - public <T, F> F reduceAux(final T initialValue, final BiFunction<E, T, T> stateAccumulator, + public <T, F> F reduceAux(final T initialValue, + final BiFunction<E, T, T> stateAccumulator, final Function<T, F> resultTransformer) { - if(stateAccumulator == null) { + if (stateAccumulator == null) { throw new NullPointerException("Accumulator must not be null"); - } else if(resultTransformer == null) { + } else if (resultTransformer == null) { throw new NullPointerException("Transformer must not be null"); } @@ -386,7 +408,8 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public boolean removeIf(final Predicate<E> removePredicate) { - if(removePredicate == null) throw new NullPointerException("Predicate must be non-null"); + if (removePredicate == null) + throw new NullPointerException("Predicate must be non-null"); return wrapped.removeIf(removePredicate); } @@ -406,7 +429,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { /* Search our internal list. */ final int foundIndex = Collections.binarySearch(wrapped, searchKey, comparator); - if(foundIndex >= 0) { + if (foundIndex >= 0) { /* We found a matching element. */ return wrapped.get(foundIndex); } @@ -439,19 +462,21 @@ public class FunctionalList<E> implements Cloneable, IList<E> { public String toString() { final int lSize = getSize(); - if(lSize == 0) return "()"; + if (lSize == 0) + return "()"; final StringBuilder sb = new StringBuilder("("); final Iterator<E> itr = toIterable().iterator(); final E itm = itr.next(); int i = 0; - if(lSize == 1) return "(" + itm + ")"; + if (lSize == 1) + return "(" + itm + ")"; - for(final E item : toIterable()) { + for (final E item : toIterable()) { sb.append(item.toString()); - if(i < lSize - 1) { + if (i < lSize - 1) { sb.append(", "); } diff --git a/src/main/java/bjc/funcdata/FunctionalMap.java b/src/main/java/bjc/funcdata/FunctionalMap.java index fc53829..aba3dd1 100644 --- a/src/main/java/bjc/funcdata/FunctionalMap.java +++ b/src/main/java/bjc/funcdata/FunctionalMap.java @@ -14,10 +14,10 @@ import bjc.data.IPair; * @author ben * * @param <KeyType> - * The type of the map's keys. + * The type of the map's keys. * * @param <ValueType> - * The type of the map's values. + * The type of the map's values. */ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { /* Our backing store. */ @@ -32,13 +32,13 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp * Create a new functional map with the specified entries. * * @param entries - * The entries to put into the map. + * The entries to put into the map. */ @SafeVarargs public FunctionalMap(final IPair<KeyType, ValueType>... entries) { this(); - for(final IPair<KeyType, ValueType> entry : entries) { + for (final IPair<KeyType, ValueType> entry : entries) { entry.doWith((key, val) -> { wrappedMap.put(key, val); }); @@ -49,10 +49,11 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp * Create a new functional map wrapping the specified map. * * @param wrap - * The map to wrap. + * The map to wrap. */ public FunctionalMap(final Map<KeyType, ValueType> wrap) { - if(wrap == null) throw new NullPointerException("Map to wrap must not be null"); + if (wrap == null) + throw new NullPointerException("Map to wrap must not be null"); wrappedMap = wrap; } @@ -89,9 +90,10 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp @Override public ValueType get(final KeyType key) { - if(key == null) throw new NullPointerException("Key must not be null"); + if (key == null) + throw new NullPointerException("Key must not be null"); - if(!wrappedMap.containsKey(key)) { + if (!wrappedMap.containsKey(key)) { final String msg = String.format("Key %s is not present in the map", key); throw new IllegalArgumentException(msg); @@ -117,15 +119,18 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp } @Override - public <MappedValue> IMap<KeyType, MappedValue> transform(final Function<ValueType, MappedValue> transformer) { - if(transformer == null) throw new NullPointerException("Transformer must not be null"); + public <MappedValue> IMap<KeyType, MappedValue> + transform(final Function<ValueType, MappedValue> transformer) { + if (transformer == null) + throw new NullPointerException("Transformer must not be null"); return new TransformedValueMap<>(this, transformer); } @Override public ValueType put(final KeyType key, final ValueType val) { - if(key == null) throw new NullPointerException("Key must not be null"); + if (key == null) + throw new NullPointerException("Key must not be null"); return wrappedMap.put(key, val); } @@ -161,15 +166,20 @@ public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueTyp @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof FunctionalMap)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof FunctionalMap)) + return false; final FunctionalMap<?, ?> other = (FunctionalMap<?, ?>) obj; - if(wrappedMap == null) { - if(other.wrappedMap != null) return false; - } else if(!wrappedMap.equals(other.wrappedMap)) return false; + if (wrappedMap == null) { + if (other.wrappedMap != null) + return false; + } else if (!wrappedMap.equals(other.wrappedMap)) + return false; return true; } } diff --git a/src/main/java/bjc/funcdata/FunctionalStringTokenizer.java b/src/main/java/bjc/funcdata/FunctionalStringTokenizer.java index 7b7c2f2..856c153 100644 --- a/src/main/java/bjc/funcdata/FunctionalStringTokenizer.java +++ b/src/main/java/bjc/funcdata/FunctionalStringTokenizer.java @@ -14,12 +14,13 @@ public class FunctionalStringTokenizer { * Create a new tokenizer from the specified string. * * @param strang - * The string to create a tokenizer from. + * The string to create a tokenizer from. * * @return A new tokenizer that splits the provided string on spaces. */ public static FunctionalStringTokenizer fromString(final String strang) { - if(strang == null) throw new NullPointerException("String to tokenize must be non-null"); + if (strang == null) + throw new NullPointerException("String to tokenize must be non-null"); return new FunctionalStringTokenizer(new StringTokenizer(strang, " ")); } @@ -31,10 +32,11 @@ public class FunctionalStringTokenizer { * Create a functional string tokenizer from a given string. * * @param inp - * The string to tokenize. + * The string to tokenize. */ public FunctionalStringTokenizer(final String inp) { - if(inp == null) throw new NullPointerException("String to tokenize must be non-null"); + if (inp == null) + throw new NullPointerException("String to tokenize must be non-null"); this.input = new StringTokenizer(inp); } @@ -44,15 +46,15 @@ public class FunctionalStringTokenizer { * separators. * * @param input - * The string to tokenize. + * The string to tokenize. * * @param seperators - * The set of separating tokens to use for splitting. + * The set of separating tokens to use for splitting. */ public FunctionalStringTokenizer(final String input, final String seperators) { - if(input == null) { + if (input == null) { throw new NullPointerException("String to tokenize must not be null"); - } else if(seperators == null) { + } else if (seperators == null) { throw new NullPointerException("Tokens to split on must not be null"); } @@ -63,10 +65,11 @@ public class FunctionalStringTokenizer { * Create a functional string tokenizer from a non-functional one. * * @param toWrap - * The non-functional string tokenizer to wrap. + * The non-functional string tokenizer to wrap. */ public FunctionalStringTokenizer(final StringTokenizer toWrap) { - if(toWrap == null) throw new NullPointerException("Wrapped tokenizer must not be null"); + if (toWrap == null) + throw new NullPointerException("Wrapped tokenizer must not be null"); this.input = toWrap; } @@ -75,12 +78,13 @@ public class FunctionalStringTokenizer { * Execute a provided action for each of the remaining tokens. * * @param action - * The action to execute for each token. + * The action to execute for each token. */ public void forEachToken(final Consumer<String> action) { - if(action == null) throw new NullPointerException("Action must not be null"); + if (action == null) + throw new NullPointerException("Action must not be null"); - while(input.hasMoreTokens()) { + while (input.hasMoreTokens()) { action.accept(input.nextToken()); } } @@ -106,11 +110,11 @@ public class FunctionalStringTokenizer { /** * Return the next token from the tokenizer. * - * @return The next token from the tokenizer, or null if no more tokens - * are available. + * @return The next token from the tokenizer, or null if no more tokens are + * available. */ public String nextToken() { - if(input.hasMoreTokens()) { + if (input.hasMoreTokens()) { /* Return the next available token. */ return input.nextToken(); } @@ -129,19 +133,20 @@ public class FunctionalStringTokenizer { } /** - * Convert the contents of this tokenizer into a list. Consumes all of - * the input from this tokenizer. + * Convert the contents of this tokenizer into a list. Consumes all of the input + * from this tokenizer. * * @param <E> - * The type of the converted tokens. + * The type of the converted tokens. * * @param transformer - * The function to use to convert tokens. + * The function to use to convert tokens. * * @return A list containing all of the converted tokens. */ public <E> IList<E> toList(final Function<String, E> transformer) { - if(transformer == null) throw new NullPointerException("Transformer must not be null"); + if (transformer == null) + throw new NullPointerException("Transformer must not be null"); final IList<E> returned = new FunctionalList<>(); diff --git a/src/main/java/bjc/funcdata/IList.java b/src/main/java/bjc/funcdata/IList.java index 38356e2..0ff8e30 100644 --- a/src/main/java/bjc/funcdata/IList.java +++ b/src/main/java/bjc/funcdata/IList.java @@ -18,14 +18,14 @@ import bjc.functypes.ID; * @author ben * * @param <ContainedType> - * The type in this list + * The type in this list */ public interface IList<ContainedType> extends Iterable<ContainedType> { /** * Add an item to this list. * * @param item - * The item to add to this list. + * The item to add to this list. * * @return Whether the item was added to the list successfully.. */ @@ -35,7 +35,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Add all of the elements in the provided list to this list. * * @param items - * The list of items to add. + * The list of items to add. * * @return True if every item was successfully added to the list, false * otherwise. @@ -48,7 +48,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Add all of the elements in the provided array to this list. * * @param items - * The array of items to add. + * The array of items to add. * * @return True if every item was successfully added to the list, false * otherwise. @@ -67,8 +67,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { } /** - * Check if all of the elements of this list match the specified - * predicate. + * Check if all of the elements of this list match the specified predicate. * * @param matcher * The predicate to use for checking. @@ -84,8 +83,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * @param matcher * The predicate to use for checking. * - * @return Whether any element in the list matches the provided - * predicate. + * @return Whether any element in the list matches the provided predicate. */ boolean anyMatch(Predicate<ContainedType> matcher); @@ -93,18 +91,18 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Reduce the contents of this list using a collector. * * @param <StateType> - * The intermediate accumulation type. + * The intermediate accumulation type. * * @param <ReducedType> - * The final, reduced type. + * The final, reduced type. * * @param collector - * The collector to use for reduction. + * The collector to use for reduction. * * @return The reduced list. */ - default <StateType, ReducedType> ReducedType collect( - final Collector<ContainedType, StateType, ReducedType> collector) { + default <StateType, ReducedType> ReducedType + collect(final Collector<ContainedType, StateType, ReducedType> collector) { final BiConsumer<StateType, ContainedType> accumulator = collector.accumulator(); final StateType initial = collector.supplier().get(); @@ -116,26 +114,25 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { } /** - * Combine this list with another one into a new list and merge the - * results. + * Combine this list with another one into a new list and merge the results. * - * Works sort of like a combined zip/map over resulting pairs. Does not - * change the underlying list. + * Works sort of like a combined zip/map over resulting pairs. Does not change + * the underlying list. * - * NOTE: The returned list will have the length of the shorter of this - * list and the combined one. + * NOTE: The returned list will have the length of the shorter of this list and + * the combined one. * * @param <OtherType> - * The type of the second list. + * The type of the second list. * * @param <CombinedType> - * The type of the combined list. + * The type of the combined list. * * @param list - * The list to combine with. + * The list to combine with. * * @param combiner - * The function to use for combining element pairs. + * The function to use for combining element pairs. * * @return A new list containing the merged pairs of lists. */ @@ -146,7 +143,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Check if the list contains the specified item. * * @param item - * The item to see if it is contained. + * The item to see if it is contained. * * @return Whether or not the specified item is in the list. */ @@ -168,40 +165,40 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { /** * Remove and return the first element from the list. - * + * * @return The first element from the list. */ ContainedType popFirst(); /** * Remove and return the last element from the list. - * + * * @return The last element from the list. */ ContainedType popLast(); /** - * Apply a function to each member of the list, then flatten the - * results. + * Apply a function to each member of the list, then flatten the results. * * Does not change the underlying list. * * @param <MappedType> - * The type of the flattened list. + * The type of the flattened list. * * @param expander - * The function to apply to each member of the list. + * The function to apply to each member of the list. * - * @return A new list containing the flattened results of applying the - * provided function. + * @return A new list containing the flattened results of applying the provided + * function. */ - <MappedType> IList<MappedType> flatMap(Function<ContainedType, IList<MappedType>> expander); + <MappedType> IList<MappedType> + flatMap(Function<ContainedType, IList<MappedType>> expander); /** * Apply a given action for each member of the list. * * @param action - * The action to apply to each member of the list. + * The action to apply to each member of the list. */ @Override void forEach(Consumer<? super ContainedType> action); @@ -210,8 +207,8 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Apply a given function to each element in the list and its index. * * @param action - * The function to apply to each element in the list and - * its index. + * The function to apply to each element in the list and its + * index. */ void forEachIndexed(BiConsumer<Integer, ContainedType> action); @@ -219,7 +216,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Retrieve a value in the list by its index. * * @param index - * The index to retrieve a value from. + * The index to retrieve a value from. * * @return The value at the specified index in the list. */ @@ -229,7 +226,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Retrieve a list containing all elements matching a predicate. * * @param predicate - * The predicate to match by. + * The predicate to match by. * * @return A list containing all elements that match the predicate. */ @@ -250,16 +247,15 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { boolean isEmpty(); /** - * Create a new list by applying the given function to each element in - * the list. + * Create a new list by applying the given function to each element in the list. * * Does not change the underlying list. * * @param <MappedType> - * The type of the transformed list. + * The type of the transformed list. * * @param transformer - * The function to apply to each element in the list. + * The function to apply to each element in the list. * * @return A new list containing the mapped elements of this list. */ @@ -269,13 +265,12 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Zip two lists into a list of pairs. * * @param <OtherType> - * The type of the second list. + * The type of the second list. * * @param list - * The list to use as the left side of the pair. + * The list to use as the left side of the pair. * - * @return A list containing pairs of this element and the specified - * list. + * @return A list containing pairs of this element and the specified list. */ <OtherType> IList<IPair<ContainedType, OtherType>> pairWith(IList<OtherType> list); @@ -283,12 +278,12 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Partition this list into a list of sublists. * * @param partitionSize - * The size of elements to put into each one of the - * sublists. - * - * @return A list partitioned into partitions of size partitionSize. The - * last partition may not be completely full if the size of the - * list is not a multiple of partitionSize. + * The size of elements to put into each one of the + * sublists. + * + * @return A list partitioned into partitions of size partitionSize. The last + * partition may not be completely full if the size of the list is not a + * multiple of partitionSize. */ IList<IList<ContainedType>> partition(int partitionSize); @@ -296,7 +291,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Prepend an item to the list. * * @param item - * The item to prepend to the list. + * The item to prepend to the list. */ void prepend(ContainedType item); @@ -304,7 +299,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Prepend an array of items to the list. * * @param items - * The items to prepend to the list. + * The items to prepend to the list. */ @SuppressWarnings("unchecked") default void prependAll(final ContainedType... items) { @@ -314,8 +309,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { } /** - * Select a random item from the list, using a default random number - * generator. + * Select a random item from the list, using a default random number generator. * * @return A random item from the list */ @@ -328,7 +322,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * generator. * * @param rnd - * The random number generator to use. + * The random number generator to use. * * @return A random element from this list. */ @@ -338,24 +332,24 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Reduce this list to a single value, using a accumulative approach. * * @param <StateType> - * The in-between type of the values + * The in-between type of the values * * @param <ReducedType> - * The final value type + * The final value type * * @param initial - * The initial value of the accumulative state. + * The initial value of the accumulative state. * * @param accumulator - * The function to use to combine a list element with the - * accumulative state. + * The function to use to combine a list element with the + * accumulative state. * * @param transformer - * The function to use to convert the accumulative state - * into a final result. + * The function to use to convert the accumulative state + * into a final result. * - * @return A single value condensed from this list and transformed into - * its final state. + * @return A single value condensed from this list and transformed into its + * final state. */ <StateType, ReducedType> ReducedType reduceAux(StateType initial, BiFunction<ContainedType, StateType, StateType> accumulator, @@ -365,15 +359,15 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Reduce this list to a single value, using a accumulative approach. * * @param <StateType> - * The in-between type of the values. + * The in-between type of the values. * * @param initial - * The initial value of the accumulative state. - * + * The initial value of the accumulative state. + * * @param accumulator - * The function to use to combine a list element with the - * accumulative state. - * + * The function to use to combine a list element with the + * accumulative state. + * * @return A single value condensed from this list. */ default <StateType> StateType reduceAux(StateType initial, @@ -385,7 +379,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Remove all elements that match a given predicate. * * @param predicate - * The predicate to use to determine elements to delete. + * The predicate to use to determine elements to delete. * * @return Whether there was anything that satisfied the predicate. */ @@ -403,32 +397,30 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { void reverse(); /** - * Perform a binary search for the specified key using the provided - * means of comparing elements. + * Perform a binary search for the specified key using the provided means of + * comparing elements. * - * Since this IS a binary search, the list must have been sorted before - * hand. + * Since this IS a binary search, the list must have been sorted before hand. * * @param key - * The key to search for. + * The key to search for. * * @param comparator - * The way to compare elements for searching. Pass null - * to use the natural ordering for E. + * The way to compare elements for searching. Pass null to use + * the natural ordering for E. * * @return The element if it is in this list, or null if it is not. */ ContainedType search(ContainedType key, Comparator<ContainedType> comparator); /** - * Sort the elements of this list using the provided way of comparing - * elements. + * Sort the elements of this list using the provided way of comparing elements. * * Does change the underlying list. * * @param comparator - * The way to compare elements for sorting. Pass null to - * use E's natural ordering + * The way to compare elements for sorting. Pass null to use + * E's natural ordering */ void sort(Comparator<ContainedType> comparator); @@ -443,7 +435,7 @@ public interface IList<ContainedType> extends Iterable<ContainedType> { * Convert this list into an array. * * @param type - * The type of array to return. + * The type of array to return. * * @return The list, as an array. */ diff --git a/src/main/java/bjc/funcdata/IMap.java b/src/main/java/bjc/funcdata/IMap.java index ba56578..dc5ee00 100644 --- a/src/main/java/bjc/funcdata/IMap.java +++ b/src/main/java/bjc/funcdata/IMap.java @@ -10,17 +10,17 @@ import java.util.function.Function; * @author ben * * @param <KeyType> - * The type of this map's keys. + * The type of this map's keys. * * @param <ValueType> - * The type of this map's values. + * The type of this map's values. */ public interface IMap<KeyType, ValueType> { /** * Execute an action for each entry in the map. * * @param action - * The action to execute for each entry in the map. + * The action to execute for each entry in the map. */ void forEach(BiConsumer<KeyType, ValueType> action); @@ -28,7 +28,7 @@ public interface IMap<KeyType, ValueType> { * Perform an action for each key in the map. * * @param action - * The action to perform on each key in the map. + * The action to perform on each key in the map. */ default void forEachKey(final Consumer<KeyType> action) { forEach((key, val) -> action.accept(key)); @@ -38,7 +38,7 @@ public interface IMap<KeyType, ValueType> { * Perform an action for each value in the map. * * @param action - * The action to perform on each value in the map. + * The action to perform on each value in the map. */ default void forEachValue(final Consumer<ValueType> action) { forEach((key, val) -> action.accept(val)); @@ -48,7 +48,7 @@ public interface IMap<KeyType, ValueType> { * Check if this map contains the specified key. * * @param key - * The key to check. + * The key to check. * * @return Whether or not the map contains the key. */ @@ -58,32 +58,31 @@ public interface IMap<KeyType, ValueType> { * Get the value assigned to the given key. * * @param key - * The key to look for a value under. + * The key to look for a value under. * * @return The value of the key. */ ValueType get(KeyType key); /** - * Get a value from the map, and return a default value if the key - * doesn't exist. + * Get a value from the map, and return a default value if the key doesn't + * exist. * * @param key - * The key to attempt to retrieve. + * The key to attempt to retrieve. * * @param defaultValue - * The value to return if the key doesn't exist. + * The value to return if the key doesn't exist. * - * @return The value associated with the key, or the default value if - * the key doesn't exist. + * @return The value associated with the key, or the default value if the key + * doesn't exist. */ default ValueType getOrDefault(final KeyType key, final ValueType defaultValue) { try { return get(key); - } catch(final IllegalArgumentException iaex) { + } catch (final IllegalArgumentException iaex) { /* - * We don't care about this, because it indicates a key - * is missing. + * We don't care about this, because it indicates a key is missing. */ return defaultValue; } @@ -93,17 +92,18 @@ public interface IMap<KeyType, ValueType> { * Add an entry to the map. * * @param key - * The key to put the value under. + * The key to put the value under. * * @param val - * The value to add. + * The value to add. * - * @return The previous value of the key in the map, or null if the key - * wasn't in the map. However, note that it may also return null - * if the key was set to null. + * @return The previous value of the key in the map, or null if the key wasn't + * in the map. However, note that it may also return null if the key was + * set to null. * * @throws UnsupportedOperationException - * If the map implementation doesn't support modifying the map. + * If the map implementation doesn't + * support modifying the map. */ ValueType put(KeyType key, ValueType val); @@ -122,22 +122,22 @@ public interface IMap<KeyType, ValueType> { } /* - * @NOTE Do we want this to be the semantics for transform, or do we - * want to go to semantics using something like Isomorphism, or doing a - * one-time bulk conversion of the values? + * @NOTE Do we want this to be the semantics for transform, or do we want to go + * to semantics using something like Isomorphism, or doing a one-time bulk + * conversion of the values? */ /** * Transform the values returned by this map. * - * NOTE: This transform is applied once for each lookup of a value, so - * the transform passed should be a proper function, or things will - * likely not work as expected. + * NOTE: This transform is applied once for each lookup of a value, so the + * transform passed should be a proper function, or things will likely not work + * as expected. * * @param <V2> - * The new type of returned values. + * The new type of returned values. * * @param transformer - * The function to use to transform values. + * The function to use to transform values. * * @return The map where each value will be transformed after lookup. */ @@ -146,8 +146,8 @@ public interface IMap<KeyType, ValueType> { } /** - * Extends this map, creating a new map that will delegate queries to - * the map, but store any added values itself. + * Extends this map, creating a new map that will delegate queries to the map, + * but store any added values itself. * * @return An extended map. */ @@ -157,12 +157,12 @@ public interface IMap<KeyType, ValueType> { * Remove the value bound to the key. * * @param key - * The key to remove from the map. + * The key to remove from the map. * - * @return The previous value for the key in the map, or null if the key - * wasn't in the class. NOTE: Just because you received null, - * doesn't mean the map wasn't changed. It may mean that someone - * put a null value for that key into the map. + * @return The previous value for the key in the map, or null if the key wasn't + * in the class. NOTE: Just because you received null, doesn't mean the + * map wasn't changed. It may mean that someone put a null value for + * that key into the map. */ ValueType remove(KeyType key); @@ -181,7 +181,7 @@ public interface IMap<KeyType, ValueType> { default IList<ValueType> valueList() { final IList<ValueType> returns = new FunctionalList<>(); - for(final KeyType key : keyList()) { + for (final KeyType key : keyList()) { returns.add(get(key)); } diff --git a/src/main/java/bjc/funcdata/SentryList.java b/src/main/java/bjc/funcdata/SentryList.java index 8a56675..b0554f5 100644 --- a/src/main/java/bjc/funcdata/SentryList.java +++ b/src/main/java/bjc/funcdata/SentryList.java @@ -8,7 +8,7 @@ import java.util.List; * @author bjculkin * * @param <T> - * The type of item in the list. + * The type of item in the list. */ public class SentryList<T> extends FunctionalList<T> { /** Create a new sentry list. */ @@ -20,7 +20,7 @@ public class SentryList<T> extends FunctionalList<T> { * Create a new sentry list backed by an existing list. * * @param backing - * The backing list. + * The backing list. */ public SentryList(final List<T> backing) { super(backing); @@ -30,7 +30,7 @@ public class SentryList<T> extends FunctionalList<T> { public boolean add(final T item) { final boolean val = super.add(item); - if(val) { + if (val) { System.out.println("Added item (" + item + ") to list"); } diff --git a/src/main/java/bjc/funcdata/TransformedValueMap.java b/src/main/java/bjc/funcdata/TransformedValueMap.java index 0f0b3b5..5de6fc3 100644 --- a/src/main/java/bjc/funcdata/TransformedValueMap.java +++ b/src/main/java/bjc/funcdata/TransformedValueMap.java @@ -10,16 +10,17 @@ import java.util.function.Function; * @author ben * * @param <OldKey> - * The type of the map's keys + * The type of the map's keys * * @param <OldValue> - * The type of the map's values + * The type of the map's values * * @param <NewValue> - * The type of the transformed values + * The type of the transformed values * */ -final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldKey, NewValue> { +final class TransformedValueMap<OldKey, OldValue, NewValue> + implements IMap<OldKey, NewValue> { /* Our backing map. */ private final IMap<OldKey, OldValue> backing; /* Our transforming function. */ @@ -29,10 +30,10 @@ final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldK * Create a new transformed-value loop. * * @param backingMap - * The map to use as backing. + * The map to use as backing. * * @param transform - * The function to use for the transform. + * The function to use for the transform. */ public TransformedValueMap(final IMap<OldKey, OldValue> backingMap, final Function<OldValue, NewValue> transform) { @@ -90,7 +91,8 @@ final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldK } @Override - public <MappedValue> IMap<OldKey, MappedValue> transform(final Function<NewValue, MappedValue> transform) { + public <MappedValue> IMap<OldKey, MappedValue> + transform(final Function<NewValue, MappedValue> transform) { return new TransformedValueMap<>(this, transform); } diff --git a/src/main/java/bjc/funcdata/bst/BinarySearchTree.java b/src/main/java/bjc/funcdata/bst/BinarySearchTree.java index d0319e4..e22a8da 100644 --- a/src/main/java/bjc/funcdata/bst/BinarySearchTree.java +++ b/src/main/java/bjc/funcdata/bst/BinarySearchTree.java @@ -14,7 +14,7 @@ import bjc.funcdata.IList; * @author ben * * @param <T> - * The data type stored in the node. + * The data type stored in the node. */ public class BinarySearchTree<T> { /* The comparator for use in ordering items */ @@ -30,10 +30,11 @@ public class BinarySearchTree<T> { * Create a new tree using the specified way to compare elements. * * @param cmp - * The thing to use for comparing elements + * The thing to use for comparing elements */ public BinarySearchTree(final Comparator<T> cmp) { - if(cmp == null) throw new NullPointerException("Comparator must not be null"); + if (cmp == null) + throw new NullPointerException("Comparator must not be null"); elementCount = 0; comparator = cmp; @@ -43,12 +44,12 @@ public class BinarySearchTree<T> { * Add a node to the binary search tree. * * @param element - * The data to add to the binary search tree. + * The data to add to the binary search tree. */ public void addNode(final T element) { elementCount++; - if(root == null) { + if (root == null) { root = new BinarySearchTreeNode<>(element, null, null); } else { root.add(element, comparator); @@ -59,18 +60,20 @@ public class BinarySearchTree<T> { * Check if an adjusted pivot falls with the bounds of a list. * * @param elements - * The list to get bounds from. + * The list to get bounds from. * * @param pivot - * The pivot. + * The pivot. * * @param pivotAdjustment - * The distance from the pivot. + * The distance from the pivot. * * @return Whether the adjusted pivot is with the list. */ - private boolean adjustedPivotInBounds(final IList<T> elements, final int pivot, final int pivotAdjustment) { - return ((pivot - pivotAdjustment) >= 0) && ((pivot + pivotAdjustment) < elements.getSize()); + private boolean adjustedPivotInBounds(final IList<T> elements, final int pivot, + final int pivotAdjustment) { + return ((pivot - pivotAdjustment) >= 0) + && ((pivot + pivotAdjustment) < elements.getSize()); } /** @@ -92,14 +95,13 @@ public class BinarySearchTree<T> { int pivotAdjustment = 0; /* Add elements until there aren't any left. */ - while(adjustedPivotInBounds(elements, pivot, pivotAdjustment)) { - if(root == null) { + while (adjustedPivotInBounds(elements, pivot, pivotAdjustment)) { + if (root == null) { /* Create a new root element. */ root = new BinarySearchTreeNode<>(elements.getByIndex(pivot), null, null); } else { /* - * Add the left and right elements in a balanced - * manner. + * Add the left and right elements in a balanced manner. */ root.add(elements.getByIndex(pivot + pivotAdjustment), comparator); root.add(elements.getByIndex(pivot - pivotAdjustment), comparator); @@ -110,9 +112,9 @@ public class BinarySearchTree<T> { } /* Add any trailing unbalanced elements. */ - if(pivot - pivotAdjustment >= 0) { + if (pivot - pivotAdjustment >= 0) { root.add(elements.getByIndex(pivot - pivotAdjustment), comparator); - } else if(pivot + pivotAdjustment < elements.getSize()) { + } else if (pivot + pivotAdjustment < elements.getSize()) { root.add(elements.getByIndex(pivot + pivotAdjustment), comparator); } } @@ -120,11 +122,11 @@ public class BinarySearchTree<T> { /** * Soft-delete a node from the tree. * - * Soft-deleted nodes stay in the tree until trim()/balance() is - * invoked, and are not included in traversals/finds. + * Soft-deleted nodes stay in the tree until trim()/balance() is invoked, and + * are not included in traversals/finds. * * @param element - * The node to delete + * The node to delete */ public void deleteNode(final T element) { elementCount--; @@ -145,7 +147,7 @@ public class BinarySearchTree<T> { * Check if a node is in the tree. * * @param element - * The node to check the presence of for the tree.. + * The node to check the presence of for the tree.. * * @return Whether or not the node is in the tree. */ @@ -157,15 +159,16 @@ public class BinarySearchTree<T> { * Traverse the tree in a specified way until the function fails. * * @param linearizationMethod - * The way to linearize the tree for traversal. + * The way to linearize the tree for traversal. * * @param traversalPredicate - * The function to use until it fails. + * The function to use until it fails. */ - public void traverse(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if(linearizationMethod == null) { + public void traverse(final TreeLinearizationMethod linearizationMethod, + final Predicate<T> traversalPredicate) { + if (linearizationMethod == null) { throw new NullPointerException("Linearization method must not be null"); - } else if(traversalPredicate == null) { + } else if (traversalPredicate == null) { throw new NullPointerException("Predicate must not be nulls"); } @@ -177,8 +180,7 @@ public class BinarySearchTree<T> { final List<T> nodes = new ArrayList<>(elementCount); /* - * Add all non-soft deleted nodes to the tree in insertion - * order. + * Add all non-soft deleted nodes to the tree in insertion order. */ traverse(TreeLinearizationMethod.PREORDER, node -> { nodes.add(node); @@ -194,7 +196,8 @@ public class BinarySearchTree<T> { @Override public String toString() { - return String.format("BinarySearchTree [elementCount=%s, root='%s']", elementCount, root); + return String.format("BinarySearchTree [elementCount=%s, root='%s']", + elementCount, root); } @Override @@ -208,16 +211,22 @@ public class BinarySearchTree<T> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof BinarySearchTree<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof BinarySearchTree<?>)) + return false; final BinarySearchTree<?> other = (BinarySearchTree<?>) obj; - if(elementCount != other.elementCount) return false; - if(root == null) { - if(other.root != null) return false; - } else if(!root.equals(other.root)) return false; + if (elementCount != other.elementCount) + return false; + if (root == null) { + if (other.root != null) + return false; + } else if (!root.equals(other.root)) + return false; return true; } diff --git a/src/main/java/bjc/funcdata/bst/BinarySearchTreeLeaf.java b/src/main/java/bjc/funcdata/bst/BinarySearchTreeLeaf.java index dfad3d9..0b99cad 100644 --- a/src/main/java/bjc/funcdata/bst/BinarySearchTreeLeaf.java +++ b/src/main/java/bjc/funcdata/bst/BinarySearchTreeLeaf.java @@ -11,7 +11,7 @@ import java.util.function.Predicate; * @author ben * * @param <T> - * The data stored in the tree. + * The data stored in the tree. */ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { /** The data held in this tree leaf */ @@ -24,7 +24,7 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { * Create a new leaf holding the specified data. * * @param element - * The data for the leaf to hold. + * The data for the leaf to hold. */ public BinarySearchTreeLeaf(final T element) { data = element; @@ -36,8 +36,10 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { } @Override - public <E> E collapse(final Function<T, E> leafTransformer, final BiFunction<E, E, E> branchCollapser) { - if(leafTransformer == null) throw new NullPointerException("Transformer must not be null"); + public <E> E collapse(final Function<T, E> leafTransformer, + final BiFunction<E, E, E> branchCollapser) { + if (leafTransformer == null) + throw new NullPointerException("Transformer must not be null"); return leafTransformer.apply(data); } @@ -54,16 +56,17 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { @Override public void delete(final T element, final Comparator<T> comparator) { - if(data.equals(element)) { + if (data.equals(element)) { isDeleted = true; } } @Override public boolean directedWalk(final DirectedWalkFunction<T> treeWalker) { - if(treeWalker == null) throw new NullPointerException("Tree walker must not be null"); + if (treeWalker == null) + throw new NullPointerException("Tree walker must not be null"); - switch(treeWalker.walk(data)) { + switch (treeWalker.walk(data)) { case SUCCESS: return true; /* We don't have any children to care about. */ @@ -78,14 +81,16 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { @Override public boolean forEach(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if(traversalPredicate == null) throw new NullPointerException("Predicate must not be null"); + if (traversalPredicate == null) + throw new NullPointerException("Predicate must not be null"); return traversalPredicate.test(data); } @Override public String toString() { - return String.format("BinarySearchTreeLeaf [data='%s', isDeleted=%s]", data, isDeleted); + return String.format("BinarySearchTreeLeaf [data='%s', isDeleted=%s]", data, + isDeleted); } @Override @@ -99,16 +104,22 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof BinarySearchTreeLeaf<?>)) return false; + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof BinarySearchTreeLeaf<?>)) + return false; final BinarySearchTreeLeaf<?> other = (BinarySearchTreeLeaf<?>) obj; - if(data == null) { - if(other.data != null) return false; - } else if(!data.equals(other.data)) return false; - if(isDeleted != other.isDeleted) return false; + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; + if (isDeleted != other.isDeleted) + return false; return true; } diff --git a/src/main/java/bjc/funcdata/bst/BinarySearchTreeNode.java b/src/main/java/bjc/funcdata/bst/BinarySearchTreeNode.java index 0453f80..a73f81a 100644 --- a/src/main/java/bjc/funcdata/bst/BinarySearchTreeNode.java +++ b/src/main/java/bjc/funcdata/bst/BinarySearchTreeNode.java @@ -16,7 +16,7 @@ import java.util.function.Predicate; * @author ben * * @param <T> - * The data type stored in the tree. + * The data type stored in the tree. */ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /* The left child of this node */ @@ -29,15 +29,16 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { * Create a new node with the specified data and children. * * @param element - * The data to store in this node. + * The data to store in this node. * * @param lft - * The left child of this node. + * The left child of this node. * * @param rght - * The right child of this node. + * The right child of this node. */ - public BinarySearchTreeNode(final T element, final ITreePart<T> lft, final ITreePart<T> rght) { + public BinarySearchTreeNode(final T element, final ITreePart<T> lft, + final ITreePart<T> rght) { super(element); this.left = lft; this.right = rght; @@ -45,24 +46,25 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public void add(final T element, final Comparator<T> comparator) { - if(comparator == null) throw new NullPointerException("Comparator must not be null"); + if (comparator == null) + throw new NullPointerException("Comparator must not be null"); - switch(comparator.compare(data, element)) { + switch (comparator.compare(data, element)) { case -1: - if(left == null) { + if (left == null) { left = new BinarySearchTreeNode<>(element, null, null); } else { left.add(element, comparator); } break; case 0: - if(isDeleted) { + if (isDeleted) { isDeleted = false; } else throw new IllegalArgumentException("Can't add duplicate values"); break; case 1: - if(right == null) { + if (right == null) { right = new BinarySearchTreeNode<>(element, null, null); } else { right.add(element, comparator); @@ -74,17 +76,19 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public <E> E collapse(final Function<T, E> nodeCollapser, final BiFunction<E, E, E> branchCollapser) { - if(nodeCollapser == null || branchCollapser == null) + public <E> E collapse(final Function<T, E> nodeCollapser, + final BiFunction<E, E, E> branchCollapser) { + if (nodeCollapser == null || branchCollapser == null) throw new NullPointerException("Collapser must not be null"); final E collapsedNode = nodeCollapser.apply(data); - if(left != null) { + if (left != null) { final E collapsedLeftBranch = left.collapse(nodeCollapser, branchCollapser); - if(right != null) { - final E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); + if (right != null) { + final E collapsedRightBranch + = right.collapse(nodeCollapser, branchCollapser); final E collapsedBranches = branchCollapser.apply(collapsedLeftBranch, collapsedRightBranch); @@ -95,7 +99,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return branchCollapser.apply(collapsedNode, collapsedLeftBranch); } - if(right != null) { + if (right != null) { final E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); return branchCollapser.apply(collapsedNode, collapsedRightBranch); @@ -106,10 +110,11 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public boolean contains(final T element, final Comparator<T> comparator) { - if(comparator == null) throw new NullPointerException("Comparator must not be null"); + if (comparator == null) + throw new NullPointerException("Comparator must not be null"); return directedWalk(currentElement -> { - switch(comparator.compare(element, currentElement)) { + switch (comparator.compare(element, currentElement)) { case -1: return LEFT; case 0: @@ -124,10 +129,11 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public void delete(final T element, final Comparator<T> comparator) { - if(comparator == null) throw new NullPointerException("Comparator must not be null"); + if (comparator == null) + throw new NullPointerException("Comparator must not be null"); directedWalk(currentElement -> { - switch(comparator.compare(data, element)) { + switch (comparator.compare(data, element)) { case -1: return left == null ? FAILURE : LEFT; case 0: @@ -143,9 +149,10 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public boolean directedWalk(final DirectedWalkFunction<T> treeWalker) { - if(treeWalker == null) throw new NullPointerException("Walker must not be null"); + if (treeWalker == null) + throw new NullPointerException("Walker must not be null"); - switch(treeWalker.walk(data)) { + switch (treeWalker.walk(data)) { case SUCCESS: return true; case LEFT: @@ -161,13 +168,13 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public boolean forEach(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if(linearizationMethod == null) { + if (linearizationMethod == null) { throw new NullPointerException("Linearization method must not be null"); - } else if(traversalPredicate == null) { + } else if (traversalPredicate == null) { throw new NullPointerException("Predicate must not be null"); } - switch(linearizationMethod) { + switch (linearizationMethod) { case PREORDER: return preorderTraverse(linearizationMethod, traversalPredicate); case INORDER: @@ -175,8 +182,9 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { case POSTORDER: return postorderTraverse(linearizationMethod, traversalPredicate); default: - String msg = String.format("Passed an incorrect TreeLinearizationMethod %s. WAT", - linearizationMethod); + String msg + = String.format("Passed an incorrect TreeLinearizationMethod %s. WAT", + linearizationMethod); throw new IllegalArgumentException(msg); } @@ -185,11 +193,14 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /* Do an in-order traversal. */ private boolean inorderTraverse(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if(!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; + if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) + return false; - if(!traverseElement(traversalPredicate)) return false; + if (!traverseElement(traversalPredicate)) + return false; - if(!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; + if (!traverseRightBranch(linearizationMethod, traversalPredicate)) + return false; return true; } @@ -197,11 +208,14 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /* Do a post-order traversal. */ private boolean postorderTraverse(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if(!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; + if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) + return false; - if(!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; + if (!traverseRightBranch(linearizationMethod, traversalPredicate)) + return false; - if(!traverseElement(traversalPredicate)) return false; + if (!traverseElement(traversalPredicate)) + return false; return true; @@ -210,11 +224,14 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /* Do a pre-order traversal. */ private boolean preorderTraverse(final TreeLinearizationMethod linearizationMethod, final Predicate<T> traversalPredicate) { - if(!traverseElement(traversalPredicate)) return false; + if (!traverseElement(traversalPredicate)) + return false; - if(!traverseLeftBranch(linearizationMethod, traversalPredicate)) return false; + if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) + return false; - if(!traverseRightBranch(linearizationMethod, traversalPredicate)) return false; + if (!traverseRightBranch(linearizationMethod, traversalPredicate)) + return false; return true; } @@ -223,7 +240,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { private boolean traverseElement(final Predicate<T> traversalPredicate) { boolean nodeSuccesfullyTraversed; - if(isDeleted) { + if (isDeleted) { nodeSuccesfullyTraversed = true; } else { nodeSuccesfullyTraversed = traversalPredicate.test(data); @@ -237,10 +254,11 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { final Predicate<T> traversalPredicate) { boolean leftSuccesfullyTraversed; - if(left == null) { + if (left == null) { leftSuccesfullyTraversed = true; } else { - leftSuccesfullyTraversed = left.forEach(linearizationMethod, traversalPredicate); + leftSuccesfullyTraversed + = left.forEach(linearizationMethod, traversalPredicate); } return leftSuccesfullyTraversed; @@ -251,10 +269,11 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { final Predicate<T> traversalPredicate) { boolean rightSuccesfullyTraversed; - if(right == null) { + if (right == null) { rightSuccesfullyTraversed = true; } else { - rightSuccesfullyTraversed = right.forEach(linearizationMethod, traversalPredicate); + rightSuccesfullyTraversed + = right.forEach(linearizationMethod, traversalPredicate); } return rightSuccesfullyTraversed; @@ -276,19 +295,26 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { @Override public boolean equals(final Object obj) { - if(this == obj) return true; - if(!super.equals(obj)) return false; - if(!(obj instanceof BinarySearchTreeNode<?>)) return false; + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (!(obj instanceof BinarySearchTreeNode<?>)) + return false; final BinarySearchTreeNode<?> other = (BinarySearchTreeNode<?>) obj; - if(left == null) { - if(other.left != null) return false; - } else if(!left.equals(other.left)) return false; + if (left == null) { + if (other.left != null) + return false; + } else if (!left.equals(other.left)) + return false; - if(right == null) { - if(other.right != null) return false; - } else if(!right.equals(other.right)) return false; + if (right == null) { + if (other.right != null) + return false; + } else if (!right.equals(other.right)) + return false; return true; } diff --git a/src/main/java/bjc/funcdata/bst/DirectedWalkFunction.java b/src/main/java/bjc/funcdata/bst/DirectedWalkFunction.java index ac2b918..4f64339 100644 --- a/src/main/java/bjc/funcdata/bst/DirectedWalkFunction.java +++ b/src/main/java/bjc/funcdata/bst/DirectedWalkFunction.java @@ -6,7 +6,7 @@ package bjc.funcdata.bst; * @author ben * * @param <T> - * The type of element stored in the walked tree + * The type of element stored in the walked tree */ @FunctionalInterface public interface DirectedWalkFunction<T> { @@ -19,13 +19,11 @@ public interface DirectedWalkFunction<T> { /** Specifies that the function has failed. */ FAILURE, /** - * Specifies that the function wants to move left in the tree - * next. + * Specifies that the function wants to move left in the tree next. */ LEFT, /** - * Specifies that the function wants to move right in the tree - * next. + * Specifies that the function wants to move right in the tree next. */ RIGHT, /** Specifies that the function has succesfully completed */ @@ -36,7 +34,7 @@ public interface DirectedWalkFunction<T> { * Perform a directed walk on a node of a tree. * * @param element - * The data stored in the node currently being visited. + * The data stored in the node currently being visited. * * @return The way the function wants the walk to go next. */ diff --git a/src/main/java/bjc/funcdata/bst/ITreePart.java b/src/main/java/bjc/funcdata/bst/ITreePart.java index 903965f..bac640d 100644 --- a/src/main/java/bjc/funcdata/bst/ITreePart.java +++ b/src/main/java/bjc/funcdata/bst/ITreePart.java @@ -11,18 +11,18 @@ import java.util.function.Predicate; * @author ben * * @param <T> - * The data contained in this part of the tree. + * The data contained in this part of the tree. */ public interface ITreePart<T> { /** * Add a element below this tree part somewhere. * * @param element - * The element to add below this tree part + * The element to add below this tree part * * @param comparator - * The thing to use for comparing values to find where to insert - * the tree part. + * The thing to use for comparing values to find where to + * insert the tree part. */ public void add(T element, Comparator<T> comparator); @@ -32,30 +32,32 @@ public interface ITreePart<T> { * Does not change the underlying tree. * * @param <E> - * The type of the final collapsed value + * The type of the final collapsed value * * @param nodeCollapser - * The function to use to transform data into mapped form. + * The function to use to transform data into mapped + * form. * * @param branchCollapser - * The function to use to collapse data in mapped form into a - * single value. + * The function to use to collapse data in mapped form + * into a single value. * * @return A single value from collapsing the tree. */ - public <E> E collapse(Function<T, E> nodeCollapser, BiFunction<E, E, E> branchCollapser); + public <E> E collapse(Function<T, E> nodeCollapser, + BiFunction<E, E, E> branchCollapser); /** * Check if this tre part or below it contains the specified data item. * * @param element - * The data item to look for. + * The data item to look for. * * @param comparator - * The comparator to use to search for the data item. + * The comparator to use to search for the data item. * - * @return Whether or not the given item is contained in this tree part - * or its children. + * @return Whether or not the given item is contained in this tree part or its + * children. */ public boolean contains(T element, Comparator<T> comparator); @@ -70,10 +72,10 @@ public interface ITreePart<T> { * Remove the given node from this tree part and any of its children. * * @param element - * The data item to remove. + * The data item to remove. * * @param comparator - * The comparator to use to search for the data item. + * The comparator to use to search for the data item. */ public void delete(T element, Comparator<T> comparator); @@ -81,24 +83,25 @@ public interface ITreePart<T> { * Execute a directed walk through the tree. * * @param walker - * The function to use to direct the walk through the tree. + * The function to use to direct the walk through the tree. * * @return Whether the directed walk finished successfully. */ public boolean directedWalk(DirectedWalkFunction<T> walker); /** - * Execute a provided function for each element of tree it succesfully - * completes for. + * Execute a provided function for each element of tree it succesfully completes + * for. * * @param linearizationMethod - * The way to linearize the tree for executing. + * The way to linearize the tree for executing. * * @param predicate - * The predicate to apply to each element, where it returning - * false terminates traversal early. + * The predicate to apply to each element, where it + * returning false terminates traversal early. * * @return Whether the traversal finished succesfully. */ - public boolean forEach(TreeLinearizationMethod linearizationMethod, Predicate<T> predicate); + public boolean forEach(TreeLinearizationMethod linearizationMethod, + Predicate<T> predicate); } diff --git a/src/main/java/bjc/funcdata/bst/TreeLinearizationMethod.java b/src/main/java/bjc/funcdata/bst/TreeLinearizationMethod.java index 35b116b..65c013b 100644 --- a/src/main/java/bjc/funcdata/bst/TreeLinearizationMethod.java +++ b/src/main/java/bjc/funcdata/bst/TreeLinearizationMethod.java @@ -7,18 +7,18 @@ package bjc.funcdata.bst; */ public enum TreeLinearizationMethod { /** - * Visit the left side of this tree part, the tree part itself, and then - * the right part. + * Visit the left side of this tree part, the tree part itself, and then the + * right part. */ INORDER, /** - * Visit the left side of this tree part, the right side, and then the - * tree part itself. + * Visit the left side of this tree part, the right side, and then the tree part + * itself. */ POSTORDER, /** - * Visit the tree part itself, then the left side of tthis tree part and - * then the right part. + * Visit the tree part itself, then the left side of tthis tree part and then + * the right part. */ PREORDER } diff --git a/src/main/java/bjc/funcdata/theory/Bifunctor.java b/src/main/java/bjc/funcdata/theory/Bifunctor.java index b576a2b..72fccff 100644 --- a/src/main/java/bjc/funcdata/theory/Bifunctor.java +++ b/src/main/java/bjc/funcdata/theory/Bifunctor.java @@ -8,10 +8,10 @@ import java.util.function.Function; * @author ben * * @param <LeftType> - * The type stored on the 'left' of the pair. + * The type stored on the 'left' of the pair. * * @param <RightType> - * The type stored on the 'right' of the pair. + * The type stored on the 'right' of the pair. */ public interface Bifunctor<LeftType, RightType> { /** @@ -20,16 +20,16 @@ public interface Bifunctor<LeftType, RightType> { * @author EVE * * @param <OldLeft> - * The old left type. + * The old left type. * * @param <OldRight> - * The old right type. + * The old right type. * * @param <NewLeft> - * The new left type. + * The new left type. * * @param <NewRight> - * The new right type. + * The new right type. */ public interface BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> extends Function<Bifunctor<OldLeft, OldRight>, Bifunctor<NewLeft, NewRight>> { @@ -44,13 +44,13 @@ public interface Bifunctor<LeftType, RightType> { * @author EVE * * @param <OldLeft> - * The old left type. + * The old left type. * * @param <OldRight> - * The old right type. + * The old right type. * * @param <NewLeft> - * The new left type. + * The new left type. */ public interface LeftBifunctorMap<OldLeft, OldRight, NewLeft> extends BifunctorMap<OldLeft, OldRight, NewLeft, OldRight> { @@ -65,13 +65,13 @@ public interface Bifunctor<LeftType, RightType> { * @author EVE * * @param <OldLeft> - * The old left type. + * The old left type. * * @param <OldRight> - * The old right type. + * The old right type. * * @param <NewRight> - * The new right type. + * The new right type. */ public interface RightBifunctorMap<OldLeft, OldRight, NewRight> extends BifunctorMap<OldLeft, OldRight, OldLeft, NewRight> { @@ -81,40 +81,45 @@ public interface Bifunctor<LeftType, RightType> { } /** - * Lift a pair of functions to a single function that maps over both - * parts of a pair. + * Lift a pair of functions to a single function that maps over both parts of a + * pair. * * @param <OldLeft> - * The old left type of the pair. + * The old left type of the pair. * * @param <OldRight> - * The old right type of the pair. + * The old right type of the pair. * * @param <NewLeft> - * The new left type of the pair. + * The new left type of the pair. * * @param <NewRight> - * The new right type of the pair. + * The new right type of the pair. * * @param leftFunc - * The function that maps over the left of the pair. + * The function that maps over the left of the pair. * * @param rightFunc - * The function that maps over the right of the pair. + * The function that maps over the right of the pair. * * @return A function that maps over both parts of the pair. */ - public default <OldLeft, OldRight, NewLeft, NewRight> BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> bimap( - final Function<OldLeft, NewLeft> leftFunc, final Function<OldRight, NewRight> rightFunc) { - final BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> bimappedFunc = (argPair) -> { - final LeftBifunctorMap<OldLeft, OldRight, NewLeft> leftMapper = argPair.fmapLeft(leftFunc); + public default <OldLeft, OldRight, NewLeft, NewRight> + BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> + bimap(final Function<OldLeft, NewLeft> leftFunc, + final Function<OldRight, NewRight> rightFunc) { + final BifunctorMap<OldLeft, OldRight, NewLeft, NewRight> bimappedFunc + = argPair -> { + final LeftBifunctorMap<OldLeft, OldRight, NewLeft> leftMapper + = argPair.fmapLeft(leftFunc); - final Bifunctor<NewLeft, OldRight> leftMappedFunctor = leftMapper.apply(argPair); - final RightBifunctorMap<NewLeft, OldRight, NewRight> rightMapper = leftMappedFunctor - .fmapRight(rightFunc); + final Bifunctor<NewLeft, OldRight> leftMappedFunctor + = leftMapper.apply(argPair); + final RightBifunctorMap<NewLeft, OldRight, NewRight> rightMapper + = leftMappedFunctor.fmapRight(rightFunc); - return rightMapper.apply(leftMappedFunctor); - }; + return rightMapper.apply(leftMappedFunctor); + }; return bimappedFunc; } @@ -123,42 +128,43 @@ public interface Bifunctor<LeftType, RightType> { * Lift a function to operate over the left part of this pair. * * @param <OldLeft> - * The old left type of the pair. + * The old left type of the pair. * * @param <OldRight> - * The old right type of the pair. + * The old right type of the pair. * * @param <NewLeft> - * The new left type of the pair. + * The new left type of the pair. * * @param func - * The function to lift to work over the left side of the pair. + * The function to lift to work over the left side of the + * pair. * * @return The function lifted to work over the left side of bifunctors. */ - public <OldLeft, OldRight, NewLeft> LeftBifunctorMap<OldLeft, OldRight, NewLeft> fmapLeft( - Function<OldLeft, NewLeft> func); + public <OldLeft, OldRight, NewLeft> LeftBifunctorMap<OldLeft, OldRight, NewLeft> + fmapLeft(Function<OldLeft, NewLeft> func); /** * Lift a function to operate over the right part of this pair. * * @param <OldLeft> - * The old left type of the pair. + * The old left type of the pair. * * @param <OldRight> - * The old right type of the pair. + * The old right type of the pair. * * @param <NewRight> - * The new right type of the pair. + * The new right type of the pair. * * @param func - * The function to lift to work over the right side of the pair. + * The function to lift to work over the right side of the + * pair. * - * @return The function lifted to work over the right side of - * bifunctors. + * @return The function lifted to work over the right side of bifunctors. */ - public <OldLeft, OldRight, NewRight> RightBifunctorMap<OldLeft, OldRight, NewRight> fmapRight( - Function<OldRight, NewRight> func); + public <OldLeft, OldRight, NewRight> RightBifunctorMap<OldLeft, OldRight, NewRight> + fmapRight(Function<OldRight, NewRight> func); /** * Get the value contained on the left of this bifunctor. diff --git a/src/main/java/bjc/funcdata/theory/Functor.java b/src/main/java/bjc/funcdata/theory/Functor.java index 4192bf4..85a1ec7 100644 --- a/src/main/java/bjc/funcdata/theory/Functor.java +++ b/src/main/java/bjc/funcdata/theory/Functor.java @@ -9,30 +9,30 @@ import java.util.function.Function; * @author ben * * @param <ContainedType> - * The value inside the functor. + * The value inside the functor. */ public interface Functor<ContainedType> { /** * Converts a normal function to operate over values in a functor.. * - * N.B: Even though the type signature implies that you can apply the - * resulting function to any type of functor, it is only safe to call it - * on instances of the type of functor you called fmap on.. + * N.B: Even though the type signature implies that you can apply the resulting + * function to any type of functor, it is only safe to call it on instances of + * the type of functor you called fmap on.. * * @param <ArgType> - * The argument of the function. + * The argument of the function. * * @param <ReturnType> - * The return type of the function. + * The return type of the function. * * @param func - * The function to convert. + * The function to convert. * - * @return The passed in function converted to work over a particular - * type of functors. + * @return The passed in function converted to work over a particular type of + * functors. */ - public <ArgType, ReturnType> Function<Functor<ArgType>, Functor<ReturnType>> fmap( - Function<ArgType, ReturnType> func); + public <ArgType, ReturnType> Function<Functor<ArgType>, Functor<ReturnType>> + fmap(Function<ArgType, ReturnType> func); /** * Retrieve the thing inside this functor. diff --git a/src/main/java/bjc/functypes/ID.java b/src/main/java/bjc/functypes/ID.java index d88858d..f830d66 100644 --- a/src/main/java/bjc/functypes/ID.java +++ b/src/main/java/bjc/functypes/ID.java @@ -4,7 +4,7 @@ import java.util.function.UnaryOperator; /** * Identity function. - * + * * @author bjculkin */ public class ID { @@ -14,6 +14,6 @@ public class ID { * @return A identity function. */ public static <A> UnaryOperator<A> id() { - return (x) -> x; + return x -> x; } } diff --git a/src/main/java/bjc/functypes/ListFlattener.java b/src/main/java/bjc/functypes/ListFlattener.java index 2f50184..3768b84 100644 --- a/src/main/java/bjc/functypes/ListFlattener.java +++ b/src/main/java/bjc/functypes/ListFlattener.java @@ -10,7 +10,7 @@ import bjc.funcdata.IList; * @author bjculkin * * @param <S> - * The type of value in the list. + * The type of value in the list. */ public interface ListFlattener<S> extends Function<IList<S>, S> { /* diff --git a/src/test/java/bjc/TestUtils.java b/src/test/java/bjc/TestUtils.java index c325877..17d6b7a 100644 --- a/src/test/java/bjc/TestUtils.java +++ b/src/test/java/bjc/TestUtils.java @@ -6,17 +6,17 @@ import static org.junit.Assert.*; /** * Utility methods for doing testing - * + * * @author Ben Culkin */ public class TestUtils { /** * Assert an iterator provides a particular sequence of values. - * + * * @param src - * The iterator to pull values from. + * The iterator to pull values from. * @param vals - * The values to expect from the iterator. + * The values to expect from the iterator. */ @SafeVarargs public static <T> void assertIteratorEquals(Iterator<T> src, T... vals) { @@ -24,9 +24,9 @@ public class TestUtils { if (src.hasNext()) { assertEquals(vals[i], src.next()); } else { - String msg = String.format("not enough values: got %d, wanted %d", - i, vals.length); - + String msg = String.format("not enough values: got %d, wanted %d", i, + vals.length); + assertTrue(msg, false); } } @@ -34,7 +34,7 @@ public class TestUtils { /** * Assert an iterator provides a particular sequence of values. - * + * * @param src * The iterator to pull values from. * @param hasMore @@ -43,14 +43,14 @@ public class TestUtils { * The values to expect from the iterator. */ @SafeVarargs - public static <T> void assertIteratorEquals(boolean hasMore, Iterator<T> src, T... vals) { + public static <T> void assertIteratorEquals(boolean hasMore, Iterator<T> src, + T... vals) { /* * @NOTE - * - * Even though it's awkward, the boolean has to come first. - * Otherwise, there are cases where the compiler will get - * confused as to what the right value for T is, and be unable - * to pick an overload. + * + * Even though it's awkward, the boolean has to come first. Otherwise, there are + * cases where the compiler will get confused as to what the right value for T + * is, and be unable to pick an overload. */ assertIteratorEquals(src, vals); @@ -59,35 +59,35 @@ public class TestUtils { /** * Assert an iterator provides a particular sequence of values. - * + * * @param src - * The iterator to pull values from. + * The iterator to pull values from. * @param vals - * The values to expect from the iterator. + * The values to expect from the iterator. */ @SafeVarargs public static <T> void assertIteratorSet(Iterator<T> src, T... vals) { Set<T> s1 = new HashSet<>(); Set<T> s2 = new HashSet<>(); - + for (int i = 0; i < vals.length; i++) { if (src.hasNext()) { s1.add(vals[i]); s2.add(src.next()); } else { - String msg = String.format("not enough values: got %d, wanted %d", - i, vals.length); - + String msg = String.format("not enough values: got %d, wanted %d", i, + vals.length); + assertTrue(msg, false); } } - + assertEquals(s1, s2); } /** * Assert an iterator provides a particular sequence of values. - * + * * @param src * The iterator to pull values from. * @param hasMore @@ -96,28 +96,28 @@ public class TestUtils { * The values to expect from the iterator. */ @SafeVarargs - public static <T> void assertIteratorSet(boolean hasMore, Iterator<T> src, T... vals) { + public static <T> void assertIteratorSet(boolean hasMore, Iterator<T> src, + T... vals) { /* * @NOTE - * - * Even though it's awkward, the boolean has to come first. - * Otherwise, there are cases where the compiler will get - * confused as to what the right value for T is, and be unable - * to pick an overload. + * + * Even though it's awkward, the boolean has to come first. Otherwise, there are + * cases where the compiler will get confused as to what the right value for T + * is, and be unable to pick an overload. */ assertIteratorSet(src, vals); assertEquals("iterator not exhausted", hasMore, src.hasNext()); } - + /** * Assert that a list contains a certain set of values. - * + * * @param src - * The list to read values from. - * + * The list to read values from. + * * @param exps - * The values to expect in the list. + * The values to expect in the list. */ @SafeVarargs public static <T> void assertListEquals(List<T> src, T... exps) { @@ -135,12 +135,12 @@ public class TestUtils { * Assert a stack has the given contents. * * @param <T> - * The type of items in the stack. + * The type of items in the stack. * * @param src - * The stack to inspect. + * The stack to inspect. * @param exps - * The values that are expected. + * The values that are expected. */ public static <T> void assertStackEquals(bjc.esodata.Stack<T> src, T... exps) { assertArrayEquals(exps, src.toArray()); diff --git a/src/test/java/bjc/data/BooleanToggleTest.java b/src/test/java/bjc/data/BooleanToggleTest.java index 3fb4490..bf7a04f 100644 --- a/src/test/java/bjc/data/BooleanToggleTest.java +++ b/src/test/java/bjc/data/BooleanToggleTest.java @@ -6,6 +6,7 @@ import org.junit.Test; /** * Test for boolean toggles. + * * @author bjculkin * */ @@ -17,7 +18,7 @@ public class BooleanToggleTest { @Test public void test() { BooleanToggle tog = new BooleanToggle(); - + // Check initial value is false. assertEquals(false, tog.peek()); // Check that 'get' returns the old value @@ -27,9 +28,9 @@ public class BooleanToggleTest { // Check that we can round-trip back. assertEquals(true, tog.get()); assertEquals(false, tog.peek()); - + tog.set(true); - + // Check set works assertEquals(true, tog.peek()); } diff --git a/src/test/java/bjc/data/CircularIteratorTest.java b/src/test/java/bjc/data/CircularIteratorTest.java index 289c62a..dfe2a17 100644 --- a/src/test/java/bjc/data/CircularIteratorTest.java +++ b/src/test/java/bjc/data/CircularIteratorTest.java @@ -6,9 +6,10 @@ import java.util.Arrays; import java.util.List; import org.junit.Test; + /** * Test for circular iterators., - * + * * @author bjculkin * */ diff --git a/src/test/java/bjc/data/QueuedIteratorTest.java b/src/test/java/bjc/data/QueuedIteratorTest.java index ef83469..b880f97 100644 --- a/src/test/java/bjc/data/QueuedIteratorTest.java +++ b/src/test/java/bjc/data/QueuedIteratorTest.java @@ -9,7 +9,7 @@ import static bjc.data.QueuedIterator.queued; /** * Test of QueuedIterator. - * + * * @author bjculkin * */ @@ -23,7 +23,8 @@ public class QueuedIteratorTest { assertIteratorEquals(false, queued()); assertIteratorEquals(false, queued(1, 2, 3), 1, 2, 3); - assertIteratorEquals(false, queued(asList(1, 2, 3), asList(3, 2, 1)), 1, 2, 3, 3, 2, 1); + assertIteratorEquals(false, queued(asList(1, 2, 3), asList(3, 2, 1)), 1, 2, 3, 3, + 2, 1); } @@ -54,7 +55,7 @@ public class QueuedIteratorTest { assertIteratorEquals(false, itr, 3, 1, 2, 3); } - + /** * Test of last() method. */ diff --git a/src/test/java/bjc/esodata/StackTest.java b/src/test/java/bjc/esodata/StackTest.java index 5dfe7d5..c6e8e21 100644 --- a/src/test/java/bjc/esodata/StackTest.java +++ b/src/test/java/bjc/esodata/StackTest.java @@ -131,7 +131,7 @@ public class StackTest { assertStackEquals(st, "a", "a", "a", "a", "b", "a", "a"); st.drop(6); - + assertStackEquals(st, "a"); st.push("b"); @@ -173,7 +173,7 @@ public class StackTest { assertStackEquals(stk, 4, 3, 2); - stk.dip((st) -> { + stk.dip(st -> { int x = stk.pop(); int y = stk.pop(); @@ -182,13 +182,13 @@ public class StackTest { assertStackEquals(stk, 4, 5); - stk.dip(2, (st) -> { + stk.dip(2, st -> { stk.push(6); }); assertStackEquals(stk, 4, 5, 6); - stk.keep((st) -> { + stk.keep(st -> { int v = st.pop(); st.push(v + 1); @@ -196,12 +196,12 @@ public class StackTest { assertStackEquals(stk, 4, 5, 5, 6); - stk.multicleave(2, (st) -> { + stk.multicleave(2, st -> { int x = st.pop(); int y = st.pop(); st.push(x + y); - }, (st) -> { + }, st -> { int x = st.pop(); int y = st.pop(); @@ -210,12 +210,12 @@ public class StackTest { assertStackEquals(stk, 1, 9, 5, 6); - stk.spread((st) -> { + stk.spread(st -> { int x = st.pop(); int y = st.pop(); st.push(x + y); - }, (st) -> { + }, st -> { int y = st.pop(); st.push(y + 1); @@ -223,7 +223,7 @@ public class StackTest { assertStackEquals(stk, 10, 6, 6); - stk.apply(2, (st) -> { + stk.apply(2, st -> { int lhs = st.pop(); st.push(lhs - st.pop()); }); diff --git a/src/test/java/bjc/esodata/ThresholdSetTest.java b/src/test/java/bjc/esodata/ThresholdSetTest.java index 1f9af04..8f1b995 100644 --- a/src/test/java/bjc/esodata/ThresholdSetTest.java +++ b/src/test/java/bjc/esodata/ThresholdSetTest.java @@ -43,7 +43,9 @@ public class ThresholdSetTest { public void testContains() { ThresholdSet<String> thst = TS("1", "2", "2", "x", "z"); - int[] exps = new int[] {1, 2, -1}; + int[] exps = new int[] { + 1, 2, -1 + }; assertArrayEquals(exps, thst.containsKeys("1", "2", "y")); } |
