summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils
diff options
context:
space:
mode:
authorbculkin2442 <bjculkin@mix.wvu.edu>2016-04-22 14:48:04 -0400
committerbculkin2442 <bjculkin@mix.wvu.edu>2016-04-22 14:48:04 -0400
commit42f7d379a430aaf2fad169f0170de04072b08b10 (patch)
tree5d46b43b2d9272f4e593820ee147b3ae3f0d82b0 /BJC-Utils2/src/main/java/bjc/utils
parentb65b705c391bb772bc41269bce5243c1cc88969d (diff)
Formatting changes
Diffstat (limited to 'BJC-Utils2/src/main/java/bjc/utils')
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java30
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java10
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java20
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java8
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/cli/ICommand.java14
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHelp.java14
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java54
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java34
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java56
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java40
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java48
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java20
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/configuration/ConfigFile.java24
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/data/BoundLazy.java18
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/data/BoundLazyPair.java64
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/data/HalfBoundLazyPair.java56
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java26
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/data/IPair.java64
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java26
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java32
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/data/Pair.java12
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java14
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java68
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java48
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java120
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java36
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalList.java24
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalMap.java120
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java64
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java34
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java36
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java28
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java326
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java42
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java92
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java80
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java42
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java24
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java118
39 files changed, 1005 insertions, 981 deletions
diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java b/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java
index e816b78..09d3da7 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java
@@ -48,21 +48,6 @@ public class CLICommander {
}
/**
- * Set the initial command mode to use
- *
- * @param initialMode
- * The initial command mode to use
- */
- public void setInitialCommandMode(ICommandMode initialMode) {
- if (initialMode == null) {
- throw new NullPointerException(
- "Initial mode must be non-zero");
- }
-
- this.initialMode = initialMode;
- }
-
- /**
* Run a set of commands through this commander
*/
public void runCommands() {
@@ -105,4 +90,19 @@ public class CLICommander {
normalOutput.print("Exiting now.");
}
+
+ /**
+ * Set the initial command mode to use
+ *
+ * @param initialMode
+ * The initial command mode to use
+ */
+ public void setInitialCommandMode(ICommandMode initialMode) {
+ if (initialMode == null) {
+ throw new NullPointerException(
+ "Initial mode must be non-zero");
+ }
+
+ this.initialMode = initialMode;
+ }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java b/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java
index 76794cf..28e0347 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/cli/DelegatingCommand.java
@@ -8,6 +8,11 @@ class DelegatingCommand implements ICommand {
}
@Override
+ public ICommand createAlias() {
+ return new DelegatingCommand(delegate);
+ }
+
+ @Override
public ICommandHandler getHandler() {
return delegate.getHandler();
}
@@ -18,11 +23,6 @@ class DelegatingCommand implements ICommand {
}
@Override
- public ICommand createAlias() {
- return new DelegatingCommand(delegate);
- }
-
- @Override
public boolean isAlias() {
return true;
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java
index 3c0aef6..fad1199 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericCommand.java
@@ -26,6 +26,16 @@ public class GenericCommand implements ICommand {
this.help = new GenericHelp(description, help);
}
+ /**
+ * Create a command that is an alias to this one
+ *
+ * @return A command that is an alias to this one
+ */
+ @Override
+ public ICommand createAlias() {
+ return new DelegatingCommand(this);
+ }
+
@Override
public ICommandHandler getHandler() {
return handler;
@@ -40,14 +50,4 @@ public class GenericCommand implements ICommand {
public boolean isAlias() {
return false;
}
-
- /**
- * Create a command that is an alias to this one
- *
- * @return A command that is an alias to this one
- */
- @Override
- public ICommand createAlias() {
- return new DelegatingCommand(this);
- }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java
index f508de8..f2fb146 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/cli/GenericHelp.java
@@ -24,13 +24,13 @@ public class GenericHelp implements ICommandHelp {
}
@Override
- public String getSummary() {
- return summary;
+ public String getDescription() {
+ return description;
}
@Override
- public String getDescription() {
- return description;
+ public String getSummary() {
+ return summary;
}
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommand.java b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommand.java
index 7029829..ff15a37 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommand.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommand.java
@@ -8,6 +8,13 @@ package bjc.utils.cli;
*/
public interface ICommand {
/**
+ * Create a command that serves as an alias to this one
+ *
+ * @return A command that serves as an alias to this one
+ */
+ public ICommand createAlias();
+
+ /**
* Get the handler that executes this command
*
* @return The handler that executes this command
@@ -22,13 +29,6 @@ public interface ICommand {
public ICommandHelp getHelp();
/**
- * Create a command that serves as an alias to this one
- *
- * @return A command that serves as an alias to this one
- */
- public ICommand createAlias();
-
- /**
* Check if this command is an alias of another command
*
* @return Whether or not this command is an alias of another
diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHelp.java b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHelp.java
index ad03dac..d475335 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHelp.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandHelp.java
@@ -8,6 +8,13 @@ package bjc.utils.cli;
*/
public interface ICommandHelp {
/**
+ * Get the description of a command
+ *
+ * @return The description of a command
+ */
+ public String getDescription();
+
+ /**
* Get the summary line for a command
*
* Used for 'help commands' which gives the user a brief idea what all
@@ -16,11 +23,4 @@ public interface ICommandHelp {
* @return The summary line line for a command
*/
public String getSummary();
-
- /**
- * Get the description of a command
- *
- * @return The description of a command
- */
- public String getDescription();
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java
index 5208657..f6313af 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/cli/ICommandMode.java
@@ -9,21 +9,6 @@ package bjc.utils.cli;
*/
public interface ICommandMode {
/**
- * Process a command in this mode
- *
- * @param command
- * The command to process
- * @param args
- * A list of arguments to the command
- * @return The command mode to use for the next command. Defaults to
- * returning this, and doing nothing else
- */
- public default ICommandMode processCommand(String command,
- String[] args) {
- return this;
- };
-
- /**
* Check to see if this mode can handle the specified command
*
* @param command
@@ -33,6 +18,19 @@ public interface ICommandMode {
*/
public default boolean canHandleCommand(String command) {
return false;
+ };
+
+ /**
+ * Get the custom prompt for this mode
+ *
+ * @return the custom prompt for this mode
+ *
+ * @throws UnsupportedOperationException
+ * if this mode doesn't support a custom prompt
+ */
+ public default String getCustomPrompt() {
+ throw new UnsupportedOperationException(
+ "This mode doesn't support a custom prompt");
}
/**
@@ -45,24 +43,26 @@ public interface ICommandMode {
}
/**
- * Check if this mode uses a custom prompt
+ * Process a command in this mode
*
- * @return Whether or not this mode uses a custom prompt
+ * @param command
+ * The command to process
+ * @param args
+ * A list of arguments to the command
+ * @return The command mode to use for the next command. Defaults to
+ * returning this, and doing nothing else
*/
- public default boolean useCustomPrompt() {
- return false;
+ public default ICommandMode processCommand(String command,
+ String[] args) {
+ return this;
}
/**
- * Get the custom prompt for this mode
- *
- * @return the custom prompt for this mode
+ * Check if this mode uses a custom prompt
*
- * @throws UnsupportedOperationException
- * if this mode doesn't support a custom prompt
+ * @return Whether or not this mode uses a custom prompt
*/
- public default String getCustomPrompt() {
- throw new UnsupportedOperationException(
- "This mode doesn't support a custom prompt");
+ public default boolean useCustomPrompt() {
+ return false;
}
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java
index a946cae..9429dde 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescription.java
@@ -7,6 +7,22 @@ package bjc.utils.components;
*
*/
public class ComponentDescription implements IDescribedComponent {
+ private static void sanityCheckArgs(String name, String author,
+ String description, int version) {
+ if (name == null) {
+ throw new IllegalArgumentException(
+ "Component name can't be null");
+ } else if (author == null) {
+ throw new IllegalArgumentException(
+ "Component author can't be null");
+ } else if (description == null) {
+ throw new IllegalArgumentException(
+ "Component description can't be null");
+ } else if (version < 0) {
+ throw new IllegalArgumentException(
+ "Component version must be greater than 0");
+ }
+ }
/**
* The author of the component
*/
@@ -19,6 +35,7 @@ public class ComponentDescription implements IDescribedComponent {
* The name of the component
*/
private String name;
+
/**
* The version of the component
*/
@@ -49,23 +66,6 @@ public class ComponentDescription implements IDescribedComponent {
this.version = version;
}
- private static void sanityCheckArgs(String name, String author,
- String description, int version) {
- if (name == null) {
- throw new IllegalArgumentException(
- "Component name can't be null");
- } else if (author == null) {
- throw new IllegalArgumentException(
- "Component author can't be null");
- } else if (description == null) {
- throw new IllegalArgumentException(
- "Component description can't be null");
- } else if (version < 0) {
- throw new IllegalArgumentException(
- "Component version must be greater than 0");
- }
- }
-
@Override
public String getAuthor() {
return author;
diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java
index 52ab0b3..be0a65b 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java
@@ -31,6 +31,34 @@ public class ComponentDescriptionFileParser {
setupReaderPragmas();
}
+ private static BiConsumer<FunctionalStringTokenizer, ComponentDescriptionState> buildStringCollapserPragma(
+ String pragmaName) {
+ return (tokenizer, state) -> {
+ if (!tokenizer.hasMoreTokens()) {
+ throw new PragmaFormatException("Pragma " + pragmaName
+ + " requires one string argument");
+ }
+
+ state.setName(ListUtils
+ .collapseTokens(tokenizer.toList((strang) -> strang)));
+ };
+ }
+
+ /**
+ * Parse a component description from a stream
+ *
+ * @param inputSource
+ * The stream to parse from
+ * @return The description parsed from the stream
+ */
+ public static ComponentDescription fromStream(
+ InputStream inputSource) {
+ ComponentDescriptionState readState = reader
+ .fromStream(inputSource, new ComponentDescriptionState());
+
+ return readState.toDescription();
+ }
+
private static void setupReaderPragmas() {
reader.addPragma("name", buildStringCollapserPragma("name"));
@@ -61,32 +89,4 @@ public class ComponentDescriptionFileParser {
}
});
}
-
- private static BiConsumer<FunctionalStringTokenizer, ComponentDescriptionState> buildStringCollapserPragma(
- String pragmaName) {
- return (tokenizer, state) -> {
- if (!tokenizer.hasMoreTokens()) {
- throw new PragmaFormatException("Pragma " + pragmaName
- + " requires one string argument");
- }
-
- state.setName(ListUtils
- .collapseTokens(tokenizer.toList((strang) -> strang)));
- };
- }
-
- /**
- * Parse a component description from a stream
- *
- * @param inputSource
- * The stream to parse from
- * @return The description parsed from the stream
- */
- public static ComponentDescription fromStream(
- InputStream inputSource) {
- ComponentDescriptionState readState = reader
- .fromStream(inputSource, new ComponentDescriptionState());
-
- return readState.toDescription();
- }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java
index 7d91c84..199009c 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionState.java
@@ -16,23 +16,13 @@ public class ComponentDescriptionState {
private int version;
/**
- * Convert this state into the description it represents
- *
- * @return The description represented by this state
- */
- public ComponentDescription toDescription() {
- return new ComponentDescription(name, author, description,
- version);
- }
-
- /**
- * Set the name of this component
+ * Set the author of this component
*
- * @param name
- * The name of this component
+ * @param author
+ * The author of this component
*/
- public void setName(String name) {
- this.name = name;
+ public void setAuthor(String author) {
+ this.author = author;
}
/**
@@ -46,13 +36,13 @@ public class ComponentDescriptionState {
}
/**
- * Set the author of this component
+ * Set the name of this component
*
- * @param author
- * The author of this component
+ * @param name
+ * The name of this component
*/
- public void setAuthor(String author) {
- this.author = author;
+ public void setName(String name) {
+ this.name = name;
}
/**
@@ -64,4 +54,14 @@ public class ComponentDescriptionState {
public void setVersion(int version) {
this.version = version;
}
+
+ /**
+ * Convert this state into the description it represents
+ *
+ * @return The description represented by this state
+ */
+ public ComponentDescription toDescription() {
+ return new ComponentDescription(name, author, description,
+ version);
+ }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java b/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java
index 8b0d303..bc1b990 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java
@@ -98,27 +98,9 @@ public class FileComponentRepository<E extends IDescribedComponent>
}
}
- private void loadComponent(Function<File, E> componentReader,
- Path pth) {
- try {
- E component = componentReader.apply(pth.toFile());
-
- if (component == null) {
- throw new NullPointerException(
- "Component reader read null component");
- } else if (!components.containsKey(component.getName())) {
- components.put(component.getName(), component);
- } else {
- CLASS_LOGGER.warn("Found a duplicate component.\n"
- + "Multiple versions of the same component are not currently supported.\n"
- + "The component" + component
- + " will not be registered .");
- }
- } catch (Exception ex) {
- CLASS_LOGGER.warn("Error found reading component from file "
- + pth.toString()
- + ". This component will not be loaded", ex);
- }
+ @Override
+ public E getComponentByName(String name) {
+ return components.get(name);
}
@Override
@@ -141,8 +123,26 @@ public class FileComponentRepository<E extends IDescribedComponent>
return "Components read from directory " + sourceDirectory + ".";
}
- @Override
- public E getComponentByName(String name) {
- return components.get(name);
+ private void loadComponent(Function<File, E> componentReader,
+ Path pth) {
+ try {
+ E component = componentReader.apply(pth.toFile());
+
+ if (component == null) {
+ throw new NullPointerException(
+ "Component reader read null component");
+ } else if (!components.containsKey(component.getName())) {
+ components.put(component.getName(), component);
+ } else {
+ CLASS_LOGGER.warn("Found a duplicate component.\n"
+ + "Multiple versions of the same component are not currently supported.\n"
+ + "The component" + component
+ + " will not be registered .");
+ }
+ } catch (Exception ex) {
+ CLASS_LOGGER.warn("Error found reading component from file "
+ + pth.toString()
+ + ". This component will not be loaded", ex);
+ }
}
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java b/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java
index 348be3e..6780f2e 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java
@@ -13,6 +13,16 @@ import bjc.utils.funcdata.IFunctionalMap;
*/
public interface IComponentRepository<E extends IDescribedComponent> {
/**
+ * Get a component with a specific name
+ *
+ * @param name
+ * The name of the component to retrieve
+ * @return The named component, or null if no component with that name
+ * exists
+ */
+ public E getComponentByName(String name);
+
+ /**
* Get a list of all the registered componets
*
* @return A list of all the registered components
@@ -30,16 +40,6 @@ public interface IComponentRepository<E extends IDescribedComponent> {
public IFunctionalMap<String, E> getComponents();
/**
- * Get a component with a specific name
- *
- * @param name
- * The name of the component to retrieve
- * @return The named component, or null if no component with that name
- * exists
- */
- public E getComponentByName(String name);
-
- /**
* Get the source from which these components came
*
* @return The source from which these components came
diff --git a/BJC-Utils2/src/main/java/bjc/utils/configuration/ConfigFile.java b/BJC-Utils2/src/main/java/bjc/utils/configuration/ConfigFile.java
index 6533023..aa436ee 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/configuration/ConfigFile.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/configuration/ConfigFile.java
@@ -15,8 +15,6 @@ import javax.lang.model.SourceVersion;
*
*/
public class ConfigFile {
- private static Map<String, ConfigCategory> topLevelCategories;
-
/**
* A category in a configuration file
*
@@ -46,6 +44,18 @@ public class ConfigFile {
}
}
+ private static Map<String, ConfigCategory> topLevelCategories;
+
+ private static boolean isCommentMarker(String token) {
+ switch (token) {
+ case "#":
+ case "//":
+ return true;
+ default:
+ return false;
+ }
+ }
+
/**
* Parse the values in a config file from a stream
*
@@ -149,14 +159,4 @@ public class ConfigFile {
}
}
-
- private static boolean isCommentMarker(String token) {
- switch (token) {
- case "#":
- case "//":
- return true;
- default:
- return false;
- }
- }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/BoundLazy.java b/BJC-Utils2/src/main/java/bjc/utils/data/BoundLazy.java
index dda65a7..ce47eb9 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/data/BoundLazy.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/data/BoundLazy.java
@@ -71,6 +71,15 @@ class BoundLazy<OldType, BoundContainedType>
}
@Override
+ public String toString() {
+ if (holderBound) {
+ return boundHolder.toString();
+ }
+
+ return "(unmaterialized)";
+ }
+
+ @Override
public IHolder<BoundContainedType> transform(
UnaryOperator<BoundContainedType> transformer) {
actions.add(transformer);
@@ -87,13 +96,4 @@ class BoundLazy<OldType, BoundContainedType>
return boundHolder.unwrap(unwrapper);
}
-
- @Override
- public String toString() {
- if (holderBound) {
- return boundHolder.toString();
- }
-
- return "(unmaterialized)";
- }
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/BoundLazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/BoundLazyPair.java
index 634f2bd..a49bb9a 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/data/BoundLazyPair.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/data/BoundLazyPair.java
@@ -24,6 +24,38 @@ class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight>
}
@Override
+ public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind(
+ BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) {
+ IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(
+ boundPair);
+ IHolder<Boolean> newPairMade = new Identity<>(pairBound);
+
+ Supplier<NewLeft> leftSupp = () -> {
+ if (!newPairMade.getValue()) {
+ newPair.replace(binder.apply(leftSupplier.get(),
+ rightSupplier.get()));
+
+ newPairMade.replace(false);
+ }
+
+ return newPair.unwrap((pair) -> pair.getLeft());
+ };
+
+ Supplier<NewRight> rightSupp = () -> {
+ if (!newPairMade.getValue()) {
+ newPair.replace(binder.apply(leftSupplier.get(),
+ rightSupplier.get()));
+
+ newPairMade.replace(false);
+ }
+
+ return newPair.unwrap((pair) -> pair.getRight());
+ };
+
+ return new BoundLazyPair<>(leftSupp, rightSupp, bindr);
+ }
+
+ @Override
public <BoundLeft> IPair<BoundLeft, NewRight> bindLeft(
Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) {
Supplier<NewLeft> leftSupp = () -> {
@@ -58,38 +90,6 @@ class BoundLazyPair<OldLeft, OldRight, NewLeft, NewRight>
}
@Override
- public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind(
- BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) {
- IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(
- boundPair);
- IHolder<Boolean> newPairMade = new Identity<>(pairBound);
-
- Supplier<NewLeft> leftSupp = () -> {
- if (!newPairMade.getValue()) {
- newPair.replace(binder.apply(leftSupplier.get(),
- rightSupplier.get()));
-
- newPairMade.replace(false);
- }
-
- return newPair.unwrap((pair) -> pair.getLeft());
- };
-
- Supplier<NewRight> rightSupp = () -> {
- if (!newPairMade.getValue()) {
- newPair.replace(binder.apply(leftSupplier.get(),
- rightSupplier.get()));
-
- newPairMade.replace(false);
- }
-
- return newPair.unwrap((pair) -> pair.getRight());
- };
-
- return new BoundLazyPair<>(leftSupp, rightSupp, bindr);
- }
-
- @Override
public <MergedType> MergedType merge(
BiFunction<NewLeft, NewRight, MergedType> merger) {
if (!pairBound) {
diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/HalfBoundLazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/HalfBoundLazyPair.java
index f32f58f..037dddf 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/data/HalfBoundLazyPair.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/data/HalfBoundLazyPair.java
@@ -20,6 +20,34 @@ class HalfBoundLazyPair<OldType, NewLeft, NewRight>
}
@Override
+ public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind(
+ BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) {
+ IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(
+ boundPair);
+ IHolder<Boolean> newPairMade = new Identity<>(pairBound);
+
+ Supplier<NewLeft> leftSupp = () -> {
+ if (!newPairMade.getValue()) {
+ newPair.replace(binder.apply(oldSupplier.get()));
+ newPairMade.replace(true);
+ }
+
+ return newPair.unwrap((pair) -> pair.getLeft());
+ };
+
+ Supplier<NewRight> rightSupp = () -> {
+ if (!newPairMade.getValue()) {
+ newPair.replace(binder.apply(oldSupplier.get()));
+ newPairMade.replace(true);
+ }
+
+ return newPair.unwrap((pair) -> pair.getRight());
+ };
+
+ return new BoundLazyPair<>(leftSupp, rightSupp, bindr);
+ }
+
+ @Override
public <BoundLeft> IPair<BoundLeft, NewRight> bindLeft(
Function<NewLeft, IPair<BoundLeft, NewRight>> leftBinder) {
Supplier<NewLeft> leftSupp = () -> {
@@ -52,34 +80,6 @@ class HalfBoundLazyPair<OldType, NewLeft, NewRight>
}
@Override
- public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind(
- BiFunction<NewLeft, NewRight, IPair<BoundLeft, BoundRight>> bindr) {
- IHolder<IPair<NewLeft, NewRight>> newPair = new Identity<>(
- boundPair);
- IHolder<Boolean> newPairMade = new Identity<>(pairBound);
-
- Supplier<NewLeft> leftSupp = () -> {
- if (!newPairMade.getValue()) {
- newPair.replace(binder.apply(oldSupplier.get()));
- newPairMade.replace(true);
- }
-
- return newPair.unwrap((pair) -> pair.getLeft());
- };
-
- Supplier<NewRight> rightSupp = () -> {
- if (!newPairMade.getValue()) {
- newPair.replace(binder.apply(oldSupplier.get()));
- newPairMade.replace(true);
- }
-
- return newPair.unwrap((pair) -> pair.getRight());
- };
-
- return new BoundLazyPair<>(leftSupp, rightSupp, bindr);
- }
-
- @Override
public <MergedType> MergedType merge(
BiFunction<NewLeft, NewRight, MergedType> merger) {
if (!pairBound) {
diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java
index 77eb899..ecf3f14 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java
@@ -64,6 +64,19 @@ public interface IHolder<ContainedType> {
Function<ContainedType, MappedType> mapper);
/**
+ * Replace the held value with a new one
+ *
+ * @param newValue
+ * The value to hold instead
+ * @return The holder itself
+ */
+ public default IHolder<ContainedType> replace(ContainedType newValue) {
+ return transform((oldValue) -> {
+ return newValue;
+ });
+ }
+
+ /**
* Transform the value held in this holder
*
* @param transformer
@@ -85,17 +98,4 @@ public interface IHolder<ContainedType> {
*/
public <UnwrappedType> UnwrappedType unwrap(
Function<ContainedType, UnwrappedType> unwrapper);
-
- /**
- * Replace the held value with a new one
- *
- * @param newValue
- * The value to hold instead
- * @return The holder itself
- */
- public default IHolder<ContainedType> replace(ContainedType newValue) {
- return transform((oldValue) -> {
- return newValue;
- });
- }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java
index ce38d60..316074e 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java
@@ -16,6 +16,20 @@ import java.util.function.Function;
*/
public interface IPair<LeftType, RightType> {
/**
+ * Bind a function across the values in this pair
+ *
+ * @param <BoundLeft>
+ * The type of the bound left
+ * @param <BoundRight>
+ * The type of the bound right
+ * @param binder
+ * The function to bind with
+ * @return The bound pair
+ */
+ 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>
@@ -40,30 +54,19 @@ public interface IPair<LeftType, RightType> {
Function<RightType, IPair<LeftType, BoundRight>> rightBinder);
/**
- * Bind a function across the values in this pair
+ * Immediately perfom the specified action with the contents of this
+ * pair
*
- * @param <BoundLeft>
- * The type of the bound left
- * @param <BoundRight>
- * The type of the bound right
- * @param binder
- * The function to bind with
- * @return The bound pair
+ * @param consumer
+ * The action to perform on the pair
*/
- public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind(
- BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder);
+ public default void doWith(BiConsumer<LeftType, RightType> consumer) {
+ merge((leftValue, rightValue) -> {
+ consumer.accept(leftValue, rightValue);
- /**
- * Merge the two values in this pair into a single value
- *
- * @param <MergedType>
- * The type of the single value
- * @param merger
- * The function to use for merging
- * @return The pair, merged into a single value
- */
- public <MergedType> MergedType merge(
- BiFunction<LeftType, RightType, MergedType> merger);
+ return null;
+ });
+ }
/**
* Get the value on the left side of the pair
@@ -84,17 +87,14 @@ public interface IPair<LeftType, RightType> {
}
/**
- * Immediately perfom the specified action with the contents of this
- * pair
+ * Merge the two values in this pair into a single value
*
- * @param consumer
- * The action to perform on the pair
+ * @param <MergedType>
+ * The type of the single value
+ * @param merger
+ * The function to use for merging
+ * @return The pair, merged into a single value
*/
- public default void doWith(BiConsumer<LeftType, RightType> consumer) {
- merge((leftValue, rightValue) -> {
- consumer.accept(leftValue, rightValue);
-
- return null;
- });
- }
+ public <MergedType> MergedType merge(
+ BiFunction<LeftType, RightType, MergedType> merger);
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java b/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java
index f4bc24a..061486e 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java
@@ -96,6 +96,19 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> {
}
@Override
+ public String toString() {
+ if (valueMaterialized) {
+ if (actions.isEmpty()) {
+ return "value[v='" + heldValue + "']";
+ }
+
+ return "value[v='" + heldValue + "'] (has pending transforms)";
+ }
+
+ return "(unmaterialized)";
+ }
+
+ @Override
public IHolder<ContainedType> transform(
UnaryOperator<ContainedType> transformer) {
actions.add(transformer);
@@ -120,17 +133,4 @@ public class Lazy<ContainedType> implements IHolder<ContainedType> {
return unwrapper.apply(heldValue);
}
-
- @Override
- public String toString() {
- if (valueMaterialized) {
- if (actions.isEmpty()) {
- return "value[v='" + heldValue + "']";
- }
-
- return "value[v='" + heldValue + "'] (has pending transforms)";
- }
-
- return "(unmaterialized)";
- }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java
index d69a7bb..b02d9cb 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java
@@ -59,6 +59,12 @@ public class LazyPair<LeftType, RightType>
}
@Override
+ public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind(
+ BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) {
+ return new BoundLazyPair<>(leftSupplier, rightSupplier, binder);
+ }
+
+ @Override
public <BoundLeft> IPair<BoundLeft, RightType> bindLeft(
Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) {
Supplier<LeftType> leftSupp = () -> {
@@ -87,49 +93,43 @@ public class LazyPair<LeftType, RightType>
}
@Override
- public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind(
- BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) {
- return new BoundLazyPair<>(leftSupplier, rightSupplier, binder);
- }
-
- @Override
- public <MergedType> MergedType merge(
- BiFunction<LeftType, RightType, MergedType> merger) {
+ public LeftType getLeft() {
if (!leftMaterialized) {
leftValue = leftSupplier.get();
leftMaterialized = true;
}
+ return leftValue;
+ }
+
+ @Override
+ public RightType getRight() {
if (!rightMaterialized) {
rightValue = rightSupplier.get();
rightMaterialized = true;
}
- return merger.apply(leftValue, rightValue);
+ return rightValue;
}
@Override
- public LeftType getLeft() {
+ public <MergedType> MergedType merge(
+ BiFunction<LeftType, RightType, MergedType> merger) {
if (!leftMaterialized) {
leftValue = leftSupplier.get();
leftMaterialized = true;
}
- return leftValue;
- }
-
- @Override
- public RightType getRight() {
if (!rightMaterialized) {
rightValue = rightSupplier.get();
rightMaterialized = true;
}
- return rightValue;
+ return merger.apply(leftValue, rightValue);
}
@Override
diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java
index 66c50de..05955b6 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java
@@ -38,6 +38,12 @@ public class Pair<LeftType, RightType>
}
@Override
+ public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind(
+ BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) {
+ return binder.apply(leftValue, rightValue);
+ }
+
+ @Override
public <BoundLeft> IPair<BoundLeft, RightType> bindLeft(
Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) {
return leftBinder.apply(leftValue);
@@ -50,12 +56,6 @@ public class Pair<LeftType, RightType>
}
@Override
- public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind(
- BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) {
- return binder.apply(leftValue, rightValue);
- }
-
- @Override
public <MergedType> MergedType merge(
BiFunction<LeftType, RightType, MergedType> merger) {
return merger.apply(leftValue, rightValue);
diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java
index 93225e1..41938a5 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java
@@ -13,6 +13,13 @@ public class PragmaFormatException extends InputMismatchException {
private static final long serialVersionUID = 1288536477368021069L;
/**
+ * Create a new exception
+ */
+ public PragmaFormatException() {
+ super();
+ }
+
+ /**
* Create a new exception with the given message
*
* @param message
@@ -21,11 +28,4 @@ public class PragmaFormatException extends InputMismatchException {
public PragmaFormatException(String message) {
super(message);
}
-
- /**
- * Create a new exception
- */
- public PragmaFormatException() {
- super();
- }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java
index 7e4c7fd..9776961 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/ExtendedMap.java
@@ -19,49 +19,47 @@ class ExtendedMap<KeyType, ValueType>
}
@Override
- public ValueType put(KeyType key, ValueType val) {
- return store.put(key, val);
- }
-
- @Override
- public ValueType get(KeyType key) {
+ public boolean containsKey(KeyType key) {
if (store.containsKey(key)) {
- return store.get(key);
+ return true;
}
- return delegate.get(key);
+ return delegate.containsKey(key);
}
@Override
- public <MappedValue> IFunctionalMap<KeyType, MappedValue> mapValues(
- Function<ValueType, MappedValue> transformer) {
- return new TransformedValueMap<>(this, transformer);
+ public IFunctionalMap<KeyType, ValueType> extend() {
+ return new ExtendedMap<>(this, new FunctionalMap<>());
}
@Override
- public boolean containsKey(KeyType key) {
- if (store.containsKey(key)) {
- return true;
- }
+ public void forEach(BiConsumer<KeyType, ValueType> action) {
+ store.forEach(action);
- return delegate.containsKey(key);
+ delegate.forEach(action);
}
@Override
- public IFunctionalList<KeyType> keyList() {
- return ListUtils.mergeLists(store.keyList(), delegate.keyList());
+ public void forEachKey(Consumer<KeyType> action) {
+ store.forEachKey(action);
+
+ delegate.forEachKey(action);
}
@Override
- public void forEach(BiConsumer<KeyType, ValueType> action) {
- store.forEach(action);
+ public void forEachValue(Consumer<ValueType> action) {
+ store.forEachValue(action);
- delegate.forEach(action);
+ delegate.forEachValue(action);
}
@Override
- public ValueType remove(KeyType key) {
- return store.remove(key);
+ public ValueType get(KeyType key) {
+ if (store.containsKey(key)) {
+ return store.get(key);
+ }
+
+ return delegate.get(key);
}
@Override
@@ -70,17 +68,24 @@ class ExtendedMap<KeyType, ValueType>
}
@Override
- public void forEachKey(Consumer<KeyType> action) {
- store.forEachKey(action);
+ public IFunctionalList<KeyType> keyList() {
+ return ListUtils.mergeLists(store.keyList(), delegate.keyList());
+ }
- delegate.forEachKey(action);
+ @Override
+ public <MappedValue> IFunctionalMap<KeyType, MappedValue> mapValues(
+ Function<ValueType, MappedValue> transformer) {
+ return new TransformedValueMap<>(this, transformer);
}
@Override
- public void forEachValue(Consumer<ValueType> action) {
- store.forEachValue(action);
+ public ValueType put(KeyType key, ValueType val) {
+ return store.put(key, val);
+ }
- delegate.forEachValue(action);
+ @Override
+ public ValueType remove(KeyType key) {
+ return store.remove(key);
}
@Override
@@ -88,9 +93,4 @@ class ExtendedMap<KeyType, ValueType>
return ListUtils.mergeLists(store.valueList(),
delegate.valueList());
}
-
- @Override
- public IFunctionalMap<KeyType, ValueType> extend() {
- return new ExtendedMap<>(this, new FunctionalMap<>());
- }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java
index c8f2269..8579693 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java
@@ -358,6 +358,15 @@ public class FunctionalList<E> implements Cloneable, IFunctionalList<E> {
}
/*
+ * Check if a partition has room for another item
+ */
+ private Boolean isPartitionFull(int numberPerPartition,
+ IHolder<IFunctionalList<E>> currentPartition) {
+ return currentPartition.unwrap(
+ (partition) -> partition.getSize() >= numberPerPartition);
+ }
+
+ /*
* (non-Javadoc)
*
* @see
@@ -433,15 +442,6 @@ public class FunctionalList<E> implements Cloneable, IFunctionalList<E> {
}
/*
- * Check if a partition has room for another item
- */
- private Boolean isPartitionFull(int numberPerPartition,
- IHolder<IFunctionalList<E>> currentPartition) {
- return currentPartition.unwrap(
- (partition) -> partition.getSize() >= numberPerPartition);
- }
-
- /*
* (non-Javadoc)
*
* @see bjc.utils.funcdata.IFunctionalList#prepend(E)
@@ -522,6 +522,11 @@ public class FunctionalList<E> implements Cloneable, IFunctionalList<E> {
removeIf((element) -> element.equals(desiredElement));
}
+ @Override
+ public void reverse() {
+ Collections.reverse(wrappedList);
+ }
+
/*
* (non-Javadoc)
*
@@ -553,6 +558,16 @@ public class FunctionalList<E> implements Cloneable, IFunctionalList<E> {
Collections.sort(wrappedList, comparator);
}
+ @Override
+ public IFunctionalList<E> tail() {
+ return new FunctionalList<>(wrappedList.subList(1, getSize()));
+ }
+
+ @Override
+ public E[] toArray(E[] arrType) {
+ return wrappedList.toArray(arrType);
+ }
+
/*
* (non-Javadoc)
*
@@ -584,19 +599,4 @@ public class FunctionalList<E> implements Cloneable, IFunctionalList<E> {
return sb.toString();
}
-
- @Override
- public E[] toArray(E[] arrType) {
- return wrappedList.toArray(arrType);
- }
-
- @Override
- public IFunctionalList<E> tail() {
- return new FunctionalList<>(wrappedList.subList(1, getSize()));
- }
-
- @Override
- public void reverse() {
- Collections.reverse(wrappedList);
- }
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java
index eaa425b..fb8bb81 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java
@@ -30,20 +30,6 @@ public class FunctionalMap<KeyType, ValueType>
}
/**
- * Create a new functional map wrapping the specified map
- *
- * @param wrap
- * The map to wrap
- */
- public FunctionalMap(Map<KeyType, ValueType> wrap) {
- if (wrap == null) {
- throw new NullPointerException("Map to wrap must not be null");
- }
-
- wrappedMap = wrap;
- }
-
- /**
* Create a new functional map with the specified entries
*
* @param entries
@@ -60,18 +46,48 @@ public class FunctionalMap<KeyType, ValueType>
}
}
+ /**
+ * Create a new functional map wrapping the specified map
+ *
+ * @param wrap
+ * The map to wrap
+ */
+ public FunctionalMap(Map<KeyType, ValueType> wrap) {
+ if (wrap == null) {
+ throw new NullPointerException("Map to wrap must not be null");
+ }
+
+ wrappedMap = wrap;
+ }
+
/*
* (non-Javadoc)
*
- * @see bjc.utils.funcdata.IFunctionalMap#put(K, V)
+ * @see bjc.utils.funcdata.IFunctionalMap#containsKey(K)
*/
@Override
- public ValueType put(KeyType key, ValueType val) {
- if (key == null) {
- throw new NullPointerException("Key must not be null");
- }
+ public boolean containsKey(KeyType key) {
+ return wrappedMap.containsKey(key);
+ }
- return wrappedMap.put(key, val);
+ @Override
+ public IFunctionalMap<KeyType, ValueType> extend() {
+ return new ExtendedMap<>(this, new FunctionalMap<>());
+ }
+
+ @Override
+ public void forEach(BiConsumer<KeyType, ValueType> action) {
+ wrappedMap.forEach(action);
+ }
+
+ @Override
+ public void forEachKey(Consumer<KeyType> action) {
+ wrappedMap.keySet().forEach(action);
+ }
+
+ @Override
+ public void forEachValue(Consumer<ValueType> action) {
+ wrappedMap.values().forEach(action);
}
/*
@@ -93,6 +109,22 @@ public class FunctionalMap<KeyType, ValueType>
return wrappedMap.get(key);
}
+ @Override
+ public int getSize() {
+ return wrappedMap.size();
+ }
+
+ @Override
+ public IFunctionalList<KeyType> keyList() {
+ FunctionalList<KeyType> keys = new FunctionalList<>();
+
+ wrappedMap.keySet().forEach((key) -> {
+ keys.add(key);
+ });
+
+ return keys;
+ }
+
/*
* (non-Javadoc)
*
@@ -112,32 +144,15 @@ public class FunctionalMap<KeyType, ValueType>
/*
* (non-Javadoc)
*
- * @see bjc.utils.funcdata.IFunctionalMap#containsKey(K)
+ * @see bjc.utils.funcdata.IFunctionalMap#put(K, V)
*/
@Override
- public boolean containsKey(KeyType key) {
- return wrappedMap.containsKey(key);
- }
-
- @Override
- public String toString() {
- return wrappedMap.toString();
- }
-
- @Override
- public IFunctionalList<KeyType> keyList() {
- FunctionalList<KeyType> keys = new FunctionalList<>();
-
- wrappedMap.keySet().forEach((key) -> {
- keys.add(key);
- });
-
- return keys;
- }
+ public ValueType put(KeyType key, ValueType val) {
+ if (key == null) {
+ throw new NullPointerException("Key must not be null");
+ }
- @Override
- public void forEach(BiConsumer<KeyType, ValueType> action) {
- wrappedMap.forEach(action);
+ return wrappedMap.put(key, val);
}
@Override
@@ -146,18 +161,8 @@ public class FunctionalMap<KeyType, ValueType>
}
@Override
- public int getSize() {
- return wrappedMap.size();
- }
-
- @Override
- public void forEachKey(Consumer<KeyType> action) {
- wrappedMap.keySet().forEach(action);
- }
-
- @Override
- public void forEachValue(Consumer<ValueType> action) {
- wrappedMap.values().forEach(action);
+ public String toString() {
+ return wrappedMap.toString();
}
@Override
@@ -170,9 +175,4 @@ public class FunctionalMap<KeyType, ValueType>
return values;
}
-
- @Override
- public IFunctionalMap<KeyType, ValueType> extend() {
- return new ExtendedMap<>(this, new FunctionalMap<>());
- }
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java
index 0e2d199..aa6fca3 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java
@@ -111,6 +111,15 @@ public class FunctionalStringTokenizer {
}
/**
+ * Check if this tokenizer has more tokens
+ *
+ * @return Whether or not this tokenizer has more tokens
+ */
+ public boolean hasMoreTokens() {
+ return input.hasMoreTokens();
+ }
+
+ /**
* Return the next token from the tokenizer. Returns null if no more
* tokens are available
*
@@ -127,6 +136,15 @@ public class FunctionalStringTokenizer {
}
/**
+ * Convert this tokenizer into a list of strings
+ *
+ * @return This tokenizer, converted into a list of strings
+ */
+ public IFunctionalList<String> toList() {
+ return toList((String element) -> element);
+ }
+
+ /**
* Convert the contents of this tokenizer into a list. Consumes all of
* the input from this tokenizer.
*
@@ -154,22 +172,4 @@ public class FunctionalStringTokenizer {
return returnList;
}
-
- /**
- * Convert this tokenizer into a list of strings
- *
- * @return This tokenizer, converted into a list of strings
- */
- public IFunctionalList<String> toList() {
- return toList((String element) -> element);
- }
-
- /**
- * Check if this tokenizer has more tokens
- *
- * @return Whether or not this tokenizer has more tokens
- */
- public boolean hasMoreTokens() {
- return input.hasMoreTokens();
- }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalList.java
index 3358da0..91b2ba3 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalList.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalList.java
@@ -286,6 +286,11 @@ public interface IFunctionalList<ContainedType> {
void removeMatching(ContainedType desiredElement);
/**
+ * Reverse the contents of this list in place
+ */
+ void reverse();
+
+ /**
* 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.
@@ -311,6 +316,13 @@ public interface IFunctionalList<ContainedType> {
void sort(Comparator<ContainedType> comparator);
/**
+ * Get the tail of this list (the list without the first element
+ *
+ * @return The list without the first element
+ */
+ public IFunctionalList<ContainedType> tail();
+
+ /**
* Convert this list into an array
*
* @param arrType
@@ -325,16 +337,4 @@ public interface IFunctionalList<ContainedType> {
* @return An iterable view onto the list
*/
Iterable<ContainedType> toIterable();
-
- /**
- * Get the tail of this list (the list without the first element
- *
- * @return The list without the first element
- */
- public IFunctionalList<ContainedType> tail();
-
- /**
- * Reverse the contents of this list in place
- */
- void reverse();
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalMap.java
index 0c96a9f..8a54246 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalMap.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IFunctionalMap.java
@@ -18,21 +18,45 @@ import java.util.function.Function;
public interface IFunctionalMap<KeyType, ValueType> {
/**
- * Add an entry to the map
+ * Check if this map contains the specified key
*
* @param key
- * The key to put the value under
- * @param val
- * 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.
+ * The key to check
+ * @return Whether or not the map contains the key
+ */
+ boolean containsKey(KeyType key);
+
+ /**
+ * Extends this map, creating a new map that will delegate queries to
+ * the map, but store any added values itself
*
- * @throws UnsupportedOperationException
- * if the map implementation doesn't support modifying the
- * map
+ * @return An extended map
*/
- ValueType put(KeyType key, ValueType val);
+ IFunctionalMap<KeyType, ValueType> extend();
+
+ /**
+ * Execute an action for each entry in the map
+ *
+ * @param action
+ * the action to execute for each entry in the map
+ */
+ void forEach(BiConsumer<KeyType, ValueType> action);
+
+ /**
+ * Perform an action for each key in the map
+ *
+ * @param action
+ * The action to perform on each key in the map
+ */
+ void forEachKey(Consumer<KeyType> action);
+
+ /**
+ * Perform an action for each value in the map
+ *
+ * @param action
+ * The action to perform on each value in the map
+ */
+ void forEachValue(Consumer<ValueType> action);
/**
* Get the value assigned to the given key
@@ -46,6 +70,20 @@ public interface IFunctionalMap<KeyType, ValueType> {
ValueType get(KeyType key);
/**
+ * Get the number of entries in this map
+ *
+ * @return The number of entries in this map
+ */
+ int getSize();
+
+ /**
+ * Get a list of all the keys in this map
+ *
+ * @return A list of all the keys in this map
+ */
+ IFunctionalList<KeyType> keyList();
+
+ /**
* Transform the values returned by this map.
*
* NOTE: This transform is applied once for each lookup of a value, so
@@ -62,28 +100,21 @@ public interface IFunctionalMap<KeyType, ValueType> {
Function<ValueType, V2> transformer);
/**
- * Check if this map contains the specified key
+ * Add an entry to the map
*
* @param key
- * The key to check
- * @return Whether or not the map contains the key
- */
- boolean containsKey(KeyType key);
-
- /**
- * Get a list of all the keys in this map
- *
- * @return A list of all the keys in this map
- */
- IFunctionalList<KeyType> keyList();
-
- /**
- * Execute an action for each entry in the map
+ * The key to put the value under
+ * @param val
+ * 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.
*
- * @param action
- * the action to execute for each entry in the map
+ * @throws UnsupportedOperationException
+ * if the map implementation doesn't support modifying the
+ * map
*/
- void forEach(BiConsumer<KeyType, ValueType> action);
+ ValueType put(KeyType key, ValueType val);
/**
* Remove the value bound to the key
@@ -98,40 +129,9 @@ public interface IFunctionalMap<KeyType, ValueType> {
ValueType remove(KeyType key);
/**
- * Get the number of entries in this map
- *
- * @return The number of entries in this map
- */
- int getSize();
-
- /**
- * Perform an action for each key in the map
- *
- * @param action
- * The action to perform on each key in the map
- */
- void forEachKey(Consumer<KeyType> action);
-
- /**
- * Perform an action for each value in the map
- *
- * @param action
- * The action to perform on each value in the map
- */
- void forEachValue(Consumer<ValueType> action);
-
- /**
* Get a list of the values in this map
*
* @return A list of values in this map
*/
IFunctionalList<ValueType> valueList();
-
- /**
- * Extends this map, creating a new map that will delegate queries to
- * the map, but store any added values itself
- *
- * @return An extended map
- */
- IFunctionalMap<KeyType, ValueType> extend();
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java
index 75557fa..1d52d82 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java
@@ -28,73 +28,73 @@ final class TransformedValueMap<OldKey, OldValue, NewValue>
}
@Override
- public NewValue get(OldKey key) {
- return transformer.apply(mapToTransform.get(key));
+ public boolean containsKey(OldKey key) {
+ return mapToTransform.containsKey(key);
}
@Override
- public boolean containsKey(OldKey key) {
- return mapToTransform.containsKey(key);
+ public IFunctionalMap<OldKey, NewValue> extend() {
+ return new ExtendedMap<>(this, new FunctionalMap<>());
}
@Override
- public String toString() {
- return mapToTransform.toString();
+ public void forEach(BiConsumer<OldKey, NewValue> action) {
+ mapToTransform.forEach((key, val) -> {
+ action.accept(key, transformer.apply(val));
+ });
}
@Override
- public NewValue put(OldKey key, NewValue val) {
- throw new UnsupportedOperationException(
- "Can't add items to transformed map");
+ public void forEachKey(Consumer<OldKey> action) {
+ mapToTransform.forEachKey(action);
}
@Override
- public <MappedValue> IFunctionalMap<OldKey, MappedValue> mapValues(
- Function<NewValue, MappedValue> transform) {
- return new TransformedValueMap<>(this, transform);
+ public void forEachValue(Consumer<NewValue> action) {
+ mapToTransform.forEachValue((val) -> {
+ action.accept(transformer.apply(val));
+ });
}
@Override
- public IFunctionalList<OldKey> keyList() {
- return mapToTransform.keyList();
+ public NewValue get(OldKey key) {
+ return transformer.apply(mapToTransform.get(key));
}
@Override
- public void forEach(BiConsumer<OldKey, NewValue> action) {
- mapToTransform.forEach((key, val) -> {
- action.accept(key, transformer.apply(val));
- });
+ public int getSize() {
+ return mapToTransform.getSize();
}
@Override
- public NewValue remove(OldKey key) {
- return transformer.apply(mapToTransform.remove(key));
+ public IFunctionalList<OldKey> keyList() {
+ return mapToTransform.keyList();
}
@Override
- public int getSize() {
- return mapToTransform.getSize();
+ public <MappedValue> IFunctionalMap<OldKey, MappedValue> mapValues(
+ Function<NewValue, MappedValue> transform) {
+ return new TransformedValueMap<>(this, transform);
}
@Override
- public void forEachKey(Consumer<OldKey> action) {
- mapToTransform.forEachKey(action);
+ public NewValue put(OldKey key, NewValue val) {
+ throw new UnsupportedOperationException(
+ "Can't add items to transformed map");
}
@Override
- public void forEachValue(Consumer<NewValue> action) {
- mapToTransform.forEachValue((val) -> {
- action.accept(transformer.apply(val));
- });
+ public NewValue remove(OldKey key) {
+ return transformer.apply(mapToTransform.remove(key));
}
@Override
- public IFunctionalList<NewValue> valueList() {
- return mapToTransform.valueList().map(transformer);
+ public String toString() {
+ return mapToTransform.toString();
}
@Override
- public IFunctionalMap<OldKey, NewValue> extend() {
- return new ExtendedMap<>(this, new FunctionalMap<>());
+ public IFunctionalList<NewValue> valueList() {
+ return mapToTransform.valueList().map(transformer);
}
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java
index c147646..712f0e3 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java
@@ -64,6 +64,23 @@ public class BinarySearchTree<T> {
}
/**
+ * Check if an adjusted pivot falls with the bounds of a list
+ *
+ * @param elements
+ * The list to get bounds from
+ * @param pivot
+ * The pivot
+ * @param pivotAdjustment
+ * The distance from the pivot
+ * @return Whether the adjusted pivot is with the list
+ */
+ private boolean adjustedPivotInBounds(IFunctionalList<T> elements,
+ int pivot, int pivotAdjustment) {
+ return (pivot - pivotAdjustment) >= 0
+ && (pivot + pivotAdjustment) < elements.getSize();
+ }
+
+ /**
* Balance the tree, and remove soft-deleted nodes for free. Takes O(N)
* time, but also O(N) space.
*/
@@ -113,23 +130,6 @@ public class BinarySearchTree<T> {
}
/**
- * Check if an adjusted pivot falls with the bounds of a list
- *
- * @param elements
- * The list to get bounds from
- * @param pivot
- * The pivot
- * @param pivotAdjustment
- * The distance from the pivot
- * @return Whether the adjusted pivot is with the list
- */
- private boolean adjustedPivotInBounds(IFunctionalList<T> elements,
- int pivot, int pivotAdjustment) {
- return (pivot - pivotAdjustment) >= 0
- && (pivot + pivotAdjustment) < elements.getSize();
- }
-
- /**
* 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.
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java
index 3374aa2..67fd5ec 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java
@@ -14,24 +14,6 @@ import bjc.utils.funcdata.IFunctionalList;
*/
public class EnumUtils {
/**
- * Get a random value from an enum
- *
- * @param <E>
- * The type of the enum
- * @param enumClass
- * The class of the enum
- * @param rnd
- * The random source to use
- * @return A random value from the specified enum
- */
- public static <E extends Enum<E>> E getRandomValue(Class<E> enumClass,
- Random rnd) {
- E[] enumValues = enumClass.getEnumConstants();
-
- return new FunctionalList<>(enumValues).randItem(rnd::nextInt);
- }
-
- /**
* Do an action for a random number of enum values
*
* @param <E>
@@ -61,4 +43,22 @@ public class EnumUtils {
valueList.forEach(action);
}
+
+ /**
+ * Get a random value from an enum
+ *
+ * @param <E>
+ * The type of the enum
+ * @param enumClass
+ * The class of the enum
+ * @param rnd
+ * The random source to use
+ * @return A random value from the specified enum
+ */
+ public static <E extends Enum<E>> E getRandomValue(Class<E> enumClass,
+ Random rnd) {
+ E[] enumValues = enumClass.getEnumConstants();
+
+ return new FunctionalList<>(enumValues).randItem(rnd::nextInt);
+ }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java
index 2119ed7..4209e6d 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java
@@ -12,20 +12,6 @@ import java.util.function.IntConsumer;
*/
public class FuncUtils {
/**
- * Do the specified action the specified number of times
- *
- * @param nTimes
- * The number of times to do the action
- * @param cons
- * The action to perform
- */
- public static void doTimes(int nTimes, IntConsumer cons) {
- for (int i = 0; i < nTimes; i++) {
- cons.accept(i);
- }
- }
-
- /**
* Convert a binary function into a unary function that returns a
* function
*
@@ -46,4 +32,18 @@ public class FuncUtils {
return func.apply(arg1, arg2);
};
}
+
+ /**
+ * Do the specified action the specified number of times
+ *
+ * @param nTimes
+ * The number of times to do the action
+ * @param cons
+ * The action to perform
+ */
+ public static void doTimes(int nTimes, IntConsumer cons) {
+ for (int i = 0; i < nTimes; i++) {
+ cons.accept(i);
+ }
+ }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java
index b0c30b3..ea15a78 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java
@@ -21,119 +21,51 @@ public class ListUtils {
private static final int MAX_NTRIESPART = 50;
/**
- * Partition a list into a list of lists, where each element can count
- * for more than one element in a partition
- *
- * @param <E>
- * The type of elements in the list to partition
+ * Collapse a string of tokens into a single string without adding any
+ * spaces
*
* @param input
- * The list to partition
- * @param elementCounter
- * The function to determine the count for each element for
- * @param numberPerPartition
- * The number of elements to put in each partition
- * @return A list partitioned according to the above rules
+ * The list of tokens to collapse
+ * @return The collapsed string of tokens
*/
- public static <E> IFunctionalList<IFunctionalList<E>> groupPartition(
- IFunctionalList<E> input, Function<E, Integer> elementCounter,
- int numberPerPartition) {
+ public static String collapseTokens(IFunctionalList<String> input) {
if (input == null) {
- throw new NullPointerException("Input list must not be null");
- } else if (elementCounter == null) {
- throw new NullPointerException("Counter must not be null");
- } else if (numberPerPartition < 1
- || numberPerPartition > input.getSize()) {
- throw new IllegalArgumentException(
- "" + numberPerPartition + " is not a valid"
- + " partition size. Must be between 1 and "
- + input.getSize());
- }
-
- /*
- * List that holds our results
- */
- IFunctionalList<IFunctionalList<E>> returnedList = new FunctionalList<>();
-
- /*
- * List that holds current partition
- */
- IHolder<IFunctionalList<E>> currentPartition = new Identity<>(
- new FunctionalList<>());
- /*
- * List that holds elements rejected during current pass
- */
- IFunctionalList<E> rejectedElements = new FunctionalList<>();
-
- /*
- * The effective number of elements in the current partitition
- */
- IHolder<Integer> numberInCurrentPartition = new Identity<>(0);
-
- /*
- * Run up to a certain number of passes
- */
- for (int numberOfIterations = 0; numberOfIterations < MAX_NTRIESPART
- && !rejectedElements.isEmpty(); numberOfIterations++) {
- input.forEach(new GroupPartIteration<>(returnedList,
- currentPartition, rejectedElements,
- numberInCurrentPartition, numberPerPartition,
- elementCounter));
-
- if (rejectedElements.isEmpty()) {
- // Nothing was rejected, so we're done
- return returnedList;
- }
+ throw new NullPointerException("Input must not be null");
}
- throw new IllegalArgumentException(
- "Heuristic (more than " + MAX_NTRIESPART
- + " iterations of partitioning) detected unpartitionable list "
- + input.toString()
- + "\nThe following elements were not partitioned: "
- + rejectedElements.toString()
- + "\nCurrent group in formation: "
- + currentPartition.unwrap((vl) -> vl.toString())
- + "\nPreviously formed groups: "
- + returnedList.toString());
+ return collapseTokens(input, "");
}
/**
- * Split tokens in a list of tokens into multiple tokens.
- *
- * The intended use is for expression parsers so that you can enter
- * something like 1+1 instead of 1 + 1.
+ * Collapse a string of tokens into a single string, adding the desired
+ * seperator after each token
*
* @param input
- * The tokens to split
- * @param operators
- * Pairs of operators to split on and regexes that match
- * those operators
- * @return A list of tokens split on all the operators
- *
+ * The list of tokens to collapse
+ * @param seperator
+ * The seperator to use for seperating tokens
+ * @return The collapsed string of tokens
*/
- public static IFunctionalList<String> splitTokens(
- IFunctionalList<String> input,
- Deque<IPair<String, String>> operators) {
+ public static String collapseTokens(IFunctionalList<String> input,
+ String seperator) {
if (input == null) {
throw new NullPointerException("Input must not be null");
- } else if (operators == null) {
- throw new NullPointerException(
- "Set of operators must not be null");
+ } else if (seperator == null) {
+ throw new NullPointerException("Seperator must not be null");
}
- IHolder<IFunctionalList<String>> returnedList = new Identity<>(
- input);
-
- operators.forEach((operator) -> {
- returnedList.transform((oldReturn) -> {
- return oldReturn.flatMap((token) -> {
- return operator.merge(new TokenSplitter(token));
- });
+ if (input.getSize() < 1) {
+ return "";
+ } else if (input.getSize() == 1) {
+ return input.first();
+ } else {
+ return input.reduceAux("", (currentString, state) -> {
+ return state + currentString + seperator;
+ }, (strang) -> {
+ return strang.substring(0,
+ strang.length() - seperator.length());
});
- });
-
- return returnedList.getValue();
+ }
}
/**
@@ -168,51 +100,42 @@ public class ListUtils {
}
/**
- * Collapse a string of tokens into a single string without adding any
- * spaces
+ * Select a number of random items from the list without replacement
*
- * @param input
- * The list of tokens to collapse
- * @return The collapsed string of tokens
+ * @param <E>
+ * The type of items to select
+ * @param list
+ * The list to select from
+ * @param numberOfItems
+ * The number of items to selet
+ * @param rng
+ * A function that creates a random number from 0 to the
+ * desired number
+ * @return A new list containing the desired number of items randomly
+ * selected from the specified list without replacement
*/
- public static String collapseTokens(IFunctionalList<String> input) {
- if (input == null) {
- throw new NullPointerException("Input must not be null");
- }
- return collapseTokens(input, "");
- }
+ public static <E> IFunctionalList<E> drawWithoutReplacement(
+ IFunctionalList<E> list, int numberOfItems,
+ Function<Integer, Integer> rng) {
+ IFunctionalList<E> selectedItems = new FunctionalList<>(
+ new ArrayList<>(numberOfItems));
- /**
- * Collapse a string of tokens into a single string, adding the desired
- * seperator after each token
- *
- * @param input
- * The list of tokens to collapse
- * @param seperator
- * The seperator to use for seperating tokens
- * @return The collapsed string of tokens
- */
- public static String collapseTokens(IFunctionalList<String> input,
- String seperator) {
- if (input == null) {
- throw new NullPointerException("Input must not be null");
- } else if (seperator == null) {
- throw new NullPointerException("Seperator must not be null");
- }
+ int totalItems = list.getSize();
- if (input.getSize() < 1) {
- return "";
- } else if (input.getSize() == 1) {
- return input.first();
- } else {
- return input.reduceAux("", (currentString, state) -> {
- return state + currentString + seperator;
- }, (strang) -> {
- return strang.substring(0,
- strang.length() - seperator.length());
- });
- }
+ list.forEachIndexed((index, element) -> {
+ int winningChance = numberOfItems - selectedItems.getSize();
+ // n - m
+ int totalChance = totalItems - (index - 1);
+ // N - t
+
+ // Probability of selecting the t+1'th element
+ if (NumberUtils.isProbable(winningChance, totalChance, rng)) {
+ selectedItems.add(element);
+ }
+ });
+
+ return selectedItems;
}
/**
@@ -244,42 +167,81 @@ public class ListUtils {
}
/**
- * Select a number of random items from the list without replacement
+ * Partition a list into a list of lists, where each element can count
+ * for more than one element in a partition
*
* @param <E>
- * The type of items to select
- * @param list
- * The list to select from
- * @param numberOfItems
- * The number of items to selet
- * @param rng
- * A function that creates a random number from 0 to the
- * desired number
- * @return A new list containing the desired number of items randomly
- * selected from the specified list without replacement
+ * The type of elements in the list to partition
+ *
+ * @param input
+ * The list to partition
+ * @param elementCounter
+ * The function to determine the count for each element for
+ * @param numberPerPartition
+ * The number of elements to put in each partition
+ * @return A list partitioned according to the above rules
*/
+ public static <E> IFunctionalList<IFunctionalList<E>> groupPartition(
+ IFunctionalList<E> input, Function<E, Integer> elementCounter,
+ int numberPerPartition) {
+ if (input == null) {
+ throw new NullPointerException("Input list must not be null");
+ } else if (elementCounter == null) {
+ throw new NullPointerException("Counter must not be null");
+ } else if (numberPerPartition < 1
+ || numberPerPartition > input.getSize()) {
+ throw new IllegalArgumentException(
+ "" + numberPerPartition + " is not a valid"
+ + " partition size. Must be between 1 and "
+ + input.getSize());
+ }
- public static <E> IFunctionalList<E> drawWithoutReplacement(
- IFunctionalList<E> list, int numberOfItems,
- Function<Integer, Integer> rng) {
- IFunctionalList<E> selectedItems = new FunctionalList<>(
- new ArrayList<>(numberOfItems));
+ /*
+ * List that holds our results
+ */
+ IFunctionalList<IFunctionalList<E>> returnedList = new FunctionalList<>();
- int totalItems = list.getSize();
+ /*
+ * List that holds current partition
+ */
+ IHolder<IFunctionalList<E>> currentPartition = new Identity<>(
+ new FunctionalList<>());
+ /*
+ * List that holds elements rejected during current pass
+ */
+ IFunctionalList<E> rejectedElements = new FunctionalList<>();
- list.forEachIndexed((index, element) -> {
- int winningChance = numberOfItems - selectedItems.getSize();
- // n - m
- int totalChance = totalItems - (index - 1);
- // N - t
+ /*
+ * The effective number of elements in the current partitition
+ */
+ IHolder<Integer> numberInCurrentPartition = new Identity<>(0);
- // Probability of selecting the t+1'th element
- if (NumberUtils.isProbable(winningChance, totalChance, rng)) {
- selectedItems.add(element);
+ /*
+ * Run up to a certain number of passes
+ */
+ for (int numberOfIterations = 0; numberOfIterations < MAX_NTRIESPART
+ && !rejectedElements.isEmpty(); numberOfIterations++) {
+ input.forEach(new GroupPartIteration<>(returnedList,
+ currentPartition, rejectedElements,
+ numberInCurrentPartition, numberPerPartition,
+ elementCounter));
+
+ if (rejectedElements.isEmpty()) {
+ // Nothing was rejected, so we're done
+ return returnedList;
}
- });
+ }
- return selectedItems;
+ throw new IllegalArgumentException(
+ "Heuristic (more than " + MAX_NTRIESPART
+ + " iterations of partitioning) detected unpartitionable list "
+ + input.toString()
+ + "\nThe following elements were not partitioned: "
+ + rejectedElements.toString()
+ + "\nCurrent group in formation: "
+ + currentPartition.unwrap((vl) -> vl.toString())
+ + "\nPreviously formed groups: "
+ + returnedList.toString());
}
/**
@@ -302,4 +264,42 @@ public class ListUtils {
return returnedList;
}
+
+ /**
+ * Split tokens in a list of tokens into multiple tokens.
+ *
+ * The intended use is for expression parsers so that you can enter
+ * something like 1+1 instead of 1 + 1.
+ *
+ * @param input
+ * The tokens to split
+ * @param operators
+ * Pairs of operators to split on and regexes that match
+ * those operators
+ * @return A list of tokens split on all the operators
+ *
+ */
+ public static IFunctionalList<String> splitTokens(
+ IFunctionalList<String> input,
+ Deque<IPair<String, String>> operators) {
+ if (input == null) {
+ throw new NullPointerException("Input must not be null");
+ } else if (operators == null) {
+ throw new NullPointerException(
+ "Set of operators must not be null");
+ }
+
+ IHolder<IFunctionalList<String>> returnedList = new Identity<>(
+ input);
+
+ operators.forEach((operator) -> {
+ returnedList.transform((oldReturn) -> {
+ return oldReturn.flatMap((token) -> {
+ return operator.merge(new TokenSplitter(token));
+ });
+ });
+ });
+
+ return returnedList.getValue();
+ }
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java
index 728968e..2f8aa09 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java
@@ -11,6 +11,27 @@ import java.util.Deque;
public class StringUtils {
/**
+ * Checks if the given expression contains the specified operator in a
+ * situation that indicates its use as an infix operator.
+ *
+ * @param expression
+ * The expression to check
+ * @param operator
+ * The operator to see if it is contained
+ * @return Whether or not the given expression contains the specified
+ * operator as a infix operator
+ */
+ public static boolean containsInfixOperator(String expression,
+ String operator) {
+ // Bit annoying to have to use a full class name, but what are you
+ // going to do?
+ return org.apache.commons.lang3.StringUtils
+ .countMatches(expression, operator) == 1
+ && !expression.equalsIgnoreCase(operator)
+ && !expression.startsWith(operator);
+ }
+
+ /**
* Check if a string consists only of one or more matches of a regular
* expression
*
@@ -40,27 +61,6 @@ public class StringUtils {
}
/**
- * Checks if the given expression contains the specified operator in a
- * situation that indicates its use as an infix operator.
- *
- * @param expression
- * The expression to check
- * @param operator
- * The operator to see if it is contained
- * @return Whether or not the given expression contains the specified
- * operator as a infix operator
- */
- public static boolean containsInfixOperator(String expression,
- String operator) {
- // Bit annoying to have to use a full class name, but what are you
- // going to do?
- return org.apache.commons.lang3.StringUtils
- .countMatches(expression, operator) == 1
- && !expression.equalsIgnoreCase(operator)
- && !expression.startsWith(operator);
- }
-
- /**
* Indent the string being built in a StringBuilder n levels
*
* @param builder
diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java
index 8d31576..131e507 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java
@@ -187,6 +187,34 @@ public class WeightedGrammar<E> {
}
/**
+ * Remove a rule with the specified name.
+ *
+ * @param name
+ * The name of the rule to remove.
+ */
+ public void deleteRule(E name) {
+ if (name == null) {
+ throw new NullPointerException("Rule name must not be null");
+ }
+
+ rules.remove(name);
+ }
+
+ /**
+ * Remove a subgrammar with the specified name.
+ *
+ * @param name
+ * The name of the subgrammar to remove.
+ */
+ public void deleteSubgrammar(E name) {
+ if (name == null) {
+ throw new NullPointerException("Rule name must not be null");
+ }
+
+ subgrammars.remove(name);
+ }
+
+ /**
* Generate a set of debug sentences for the specified rule. Only
* generates sentances one layer deep.
*
@@ -295,6 +323,24 @@ public class WeightedGrammar<E> {
}
/**
+ * Returns the number of rules in this grammar
+ *
+ * @return The number of rules in this grammar
+ */
+ public int getRuleCount() {
+ return rules.getSize();
+ }
+
+ /**
+ * Returns a set containing all of the rules in this grammar
+ *
+ * @return The set of all rule names in this grammar
+ */
+ public IFunctionalList<E> getRuleNames() {
+ return rules.keyList();
+ }
+
+ /**
* Get the subgrammar with the specified name.
*
* @param name
@@ -429,52 +475,6 @@ public class WeightedGrammar<E> {
}
/**
- * Remove a rule with the specified name.
- *
- * @param name
- * The name of the rule to remove.
- */
- public void deleteRule(E name) {
- if (name == null) {
- throw new NullPointerException("Rule name must not be null");
- }
-
- rules.remove(name);
- }
-
- /**
- * Remove a subgrammar with the specified name.
- *
- * @param name
- * The name of the subgrammar to remove.
- */
- public void deleteSubgrammar(E name) {
- if (name == null) {
- throw new NullPointerException("Rule name must not be null");
- }
-
- subgrammars.remove(name);
- }
-
- /**
- * Returns the number of rules in this grammar
- *
- * @return The number of rules in this grammar
- */
- public int getRuleCount() {
- return rules.getSize();
- }
-
- /**
- * Returns a set containing all of the rules in this grammar
- *
- * @return The set of all rule names in this grammar
- */
- public IFunctionalList<E> getRuleNames() {
- return rules.keyList();
- }
-
- /**
* Set the initial rule of the graphic
*
* @param initRule
diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java
index 58a233a..fa34083 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java
@@ -43,6 +43,43 @@ public class Edge<T> {
this.distance = distance;
}
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ } else if (obj == null) {
+ return false;
+ } else if (getClass() != obj.getClass()) {
+ return false;
+ } else {
+
+ Edge<?> other = (Edge<?>) obj;
+
+ if (distance != other.distance) {
+ return false;
+ } else if (source == null) {
+ if (other.source != null) {
+ return false;
+ }
+ } else if (!source.equals(other.source)) {
+ return false;
+ } else if (target == null) {
+ if (other.target != null) {
+ return false;
+ }
+ } else if (!target.equals(other.target)) {
+ return false;
+ }
+
+ return true;
+ }
+ }
+
/**
* Get the distance in this edge
*
@@ -71,12 +108,6 @@ public class Edge<T> {
return target;
}
- @Override
- public String toString() {
- return " first vertex " + source + " to vertex " + target
- + " with distance: " + distance;
- }
-
/*
* (non-Javadoc)
*
@@ -94,40 +125,9 @@ public class Edge<T> {
return result;
}
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#equals(java.lang.Object)
- */
@Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- } else if (obj == null) {
- return false;
- } else if (getClass() != obj.getClass()) {
- return false;
- } else {
-
- Edge<?> other = (Edge<?>) obj;
-
- if (distance != other.distance) {
- return false;
- } else if (source == null) {
- if (other.source != null) {
- return false;
- }
- } else if (!source.equals(other.source)) {
- return false;
- } else if (target == null) {
- if (other.target != null) {
- return false;
- }
- } else if (!target.equals(other.target)) {
- return false;
- }
-
- return true;
- }
+ public String toString() {
+ return " first vertex " + source + " to vertex " + target
+ + " with distance: " + distance;
}
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java
index fbaf3f6..0574325 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java
@@ -26,6 +26,27 @@ import bjc.utils.funcdata.IFunctionalMap;
*/
public class Graph<T> {
/**
+ * Create a graph from a list of edges
+ *
+ * @param <E>
+ * The type of data stored in the edges
+ *
+ * @param edges
+ * The list of edges to build from
+ * @return A graph built from the provided edge-list
+ */
+ public static <E> Graph<E> fromEdgeList(List<Edge<E>> edges) {
+ Graph<E> g = new Graph<>();
+
+ edges.forEach(edge -> {
+ g.addEdge(edge.getSource(), edge.getTarget(),
+ edge.getDistance(), true);
+ });
+
+ return g;
+ }
+
+ /**
* The backing representation of the graph
*/
private final IFunctionalMap<T, IFunctionalMap<T, Integer>> backingGraph;
@@ -265,25 +286,4 @@ public class Graph<T> {
return adjacencyMap;
}
-
- /**
- * Create a graph from a list of edges
- *
- * @param <E>
- * The type of data stored in the edges
- *
- * @param edges
- * The list of edges to build from
- * @return A graph built from the provided edge-list
- */
- public static <E> Graph<E> fromEdgeList(List<Edge<E>> edges) {
- Graph<E> g = new Graph<>();
-
- edges.forEach(edge -> {
- g.addEdge(edge.getSource(), edge.getTarget(),
- edge.getDistance(), true);
- });
-
- return g;
- }
}
diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java
index 37f7edf..51d9d5d 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java
@@ -265,4 +265,28 @@ public class SimpleDialogs {
JOptionPane.showMessageDialog(parent, errorMessage, title,
JOptionPane.ERROR_MESSAGE);
}
+
+ /**
+ * Show an informative message to the user
+ *
+ * @param parent
+ * The parent for this dialog
+ * @param title
+ * Show the title for this dialog
+ * @param message
+ * Show the message for this dialog
+ */
+ public static void showMessage(Component parent, String title,
+ String message) {
+ if (parent == null) {
+ throw new NullPointerException("Parent must not be null");
+ } else if (title == null) {
+ throw new NullPointerException("Title must not be null");
+ } else if (message == null) {
+ throw new NullPointerException("Message must not be null");
+ }
+
+ JOptionPane.showMessageDialog(parent, title, message,
+ JOptionPane.INFORMATION_MESSAGE);
+ }
} \ No newline at end of file
diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java
index a2fc34b..2b97a79 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java
@@ -71,6 +71,39 @@ public class RuleBasedConfigReader<E> {
pragmas.put(pragmaName, pragmaAction);
}
+ private void continueRule(E state, boolean ruleOpen, String line) {
+ if (ruleOpen == false) {
+ throw new InputMismatchException(
+ "Can't continue rule with no rule currently open");
+ }
+
+ if (continueRule == null) {
+ throw new InputMismatchException(
+ "Attempted to continue rule with rule continuation disabled."
+ + " Check for extraneous tabs");
+ }
+
+ continueRule.accept(
+ new FunctionalStringTokenizer(line.substring(1), " "),
+ state);
+ }
+
+ private boolean endRule(E state, boolean ruleOpen) {
+ if (ruleOpen == false) {
+ // Ignore blank line without an open rule
+ } else {
+ if (endRule == null) {
+ // Nothing happens on rule end
+ ruleOpen = false;
+ } else {
+ endRule.accept(state);
+ }
+
+ ruleOpen = false;
+ }
+ return ruleOpen;
+ }
+
/**
* Run a stream through this reader
*
@@ -114,65 +147,6 @@ public class RuleBasedConfigReader<E> {
return state;
}
- private boolean startRule(E state, boolean ruleOpen, String line) {
- FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer(
- line, " ");
-
- String nextToken = tokenizer.nextToken();
-
- if (nextToken.equals("pragma")) {
- String token = tokenizer.nextToken();
-
- pragmas.getOrDefault(token, (tokenzer, stat) -> {
- throw new UnknownPragmaException(
- "Unknown pragma " + token);
- }).accept(tokenizer, state);
- } else {
- if (ruleOpen == true) {
- throw new InputMismatchException("Attempted to open a"
- + " rule with a rule already open. Make sure rules are"
- + " seperated by blank lines");
- }
-
- startRule.accept(tokenizer, new Pair<>(nextToken, state));
- ruleOpen = true;
- }
- return ruleOpen;
- }
-
- private void continueRule(E state, boolean ruleOpen, String line) {
- if (ruleOpen == false) {
- throw new InputMismatchException(
- "Can't continue rule with no rule currently open");
- }
-
- if (continueRule == null) {
- throw new InputMismatchException(
- "Attempted to continue rule with rule continuation disabled."
- + " Check for extraneous tabs");
- }
-
- continueRule.accept(
- new FunctionalStringTokenizer(line.substring(1), " "),
- state);
- }
-
- private boolean endRule(E state, boolean ruleOpen) {
- if (ruleOpen == false) {
- // Ignore blank line without an open rule
- } else {
- if (endRule == null) {
- // Nothing happens on rule end
- ruleOpen = false;
- } else {
- endRule.accept(state);
- }
-
- ruleOpen = false;
- }
- return ruleOpen;
- }
-
/**
* Set the action to execute when continuing a rule
*
@@ -209,4 +183,30 @@ public class RuleBasedConfigReader<E> {
this.startRule = startRule;
}
+
+ private boolean startRule(E state, boolean ruleOpen, String line) {
+ FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer(
+ line, " ");
+
+ String nextToken = tokenizer.nextToken();
+
+ if (nextToken.equals("pragma")) {
+ String token = tokenizer.nextToken();
+
+ pragmas.getOrDefault(token, (tokenzer, stat) -> {
+ throw new UnknownPragmaException(
+ "Unknown pragma " + token);
+ }).accept(tokenizer, state);
+ } else {
+ if (ruleOpen == true) {
+ throw new InputMismatchException("Attempted to open a"
+ + " rule with a rule already open. Make sure rules are"
+ + " seperated by blank lines");
+ }
+
+ startRule.accept(tokenizer, new Pair<>(nextToken, state));
+ ruleOpen = true;
+ }
+ return ruleOpen;
+ }
}