|
6 | 6 | import java.util.ArrayList; |
7 | 7 | import java.util.Arrays; |
8 | 8 | import java.util.List; |
| 9 | +import java.util.function.Function; |
| 10 | +import java.util.function.Predicate; |
9 | 11 |
|
10 | 12 | public class FormulaUtils { |
11 | 13 | public static Node negate(final Node node) { |
@@ -60,7 +62,41 @@ public static void flatten(final And and) { |
60 | 62 | } while (!redundantChildren.isEmpty()); |
61 | 63 | } |
62 | 64 |
|
63 | | - public static String toString(final Node formula, final String[] symbols) { |
| 65 | + /** |
| 66 | + * Replaces all nodes within the given formula's tree that match the given predicate. |
| 67 | + * Matching nodes (i.e., nodes for which the predicate who returns true) will be replaced by the value returned |
| 68 | + * by the replacement function, invoked on the matching node. |
| 69 | + * @param root The root of the formula in which occurences of formulas should be replaced. The object remains unaltered. |
| 70 | + * @param who A replacement is made whenever this predicate evaluates to true on a given node. |
| 71 | + * @param replacement Whenever a node should be replaced, this function is invoked with that node as argument. |
| 72 | + * The node will be replaced with the node returned. |
| 73 | + * @return A new formula in which all nodes matching the given predicate are replaced. |
| 74 | + */ |
| 75 | + public static Node replaceAll(final Node root, final Predicate<Node> who, final Function<Node, Node> replacement) { |
| 76 | + return replaceAllInplace(root.clone(), who, replacement); |
| 77 | + } |
| 78 | + |
| 79 | + /** |
| 80 | + * Inplace variant of the {@link #replaceAll(Node, Predicate, Function)} function. |
| 81 | + * This means the given formula (root parameter) will be altered. |
| 82 | + */ |
| 83 | + public static Node replaceAllInplace(final Node root, final Predicate<Node> who, final Function<Node, Node> replacement) { |
| 84 | + if (who.test(root)) { |
| 85 | + return replacement.apply(root); |
| 86 | + } else { |
| 87 | + final Node[] children = root.getChildren(); |
| 88 | + for (int i = 0; i < children.length; ++i) { |
| 89 | + children[i] = replaceAllInplace(children[i], who, replacement); |
| 90 | + } |
| 91 | + root.setChildren(children); |
| 92 | + return root; |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + public static String toString(Node formula, final String[] symbols) { |
| 97 | + formula = replaceAll(formula, FixTrueFalse::isTrue, n -> FixTrueFalse.TrueAs1); |
| 98 | + formula = replaceAllInplace(formula, FixTrueFalse::isFalse, n -> FixTrueFalse.FalseAs0); |
| 99 | + |
64 | 100 | final NodeWriter writer = new NodeWriter(formula); |
65 | 101 | writer.setNotation(NodeWriter.Notation.INFIX); |
66 | 102 | writer.setEnquoteWhitespace(false); |
|
0 commit comments