Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a data structure for storing boolean expressions?

Tags:

java

I need to store Boolean expressions like this:

x1 AND x2 AND x3 OR (x4 AND x5) AND (NOT x6)

Each x variable is a Boolean expression like == or != with values. The problem is to store nested AND and OR clauses (inside themselves and/or inside each other) and wrap them with NOT. The wrapping depth can be very deep.

Does the Java SDK have data structure for these expressions?

like image 682
Cherry Avatar asked Jun 29 '16 09:06

Cherry


People also ask

What is the data type to store the Boolean value?

Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False. Boolean variables display as either: True or False (when Print is used), or. #TRUE# or #FALSE# (when Write # is used).

What is Boolean data structure?

In computer science, the Boolean (sometimes shortened to Bool) is a data type that has one of two possible values (usually denoted true and false) which is intended to represent the two truth values of logic and Boolean algebra.

Can you store the results of a Boolean expression as a variable?

For example, we can store the results of that Boolean expression in a variable: var belowFreezing = temperature < 32; Depending on the current value of temperature , the belowFreezing variable will now store either true or false .

Can Boolean data type be used?

BOOLEAN can be used as a data type when defining a column in a table or a variable in a database procedure. Support for the BOOLEAN data type helps migrations from other database products. Boolean columns accept as input the SQL literals FALSE and TRUE.


1 Answers

In Java 8 the functional interface Predicate<T> is the way to go.

Here are the Java docs.

And here are various examples.

So in your use case it will be something as follows:

public static Predicate<Integer> equals(Integer compare) {
    return i -> i.equals(compare);
}

public static Predicate<Integer> complex() {
    return equals(1).and(equals(2)).and(equals(3)).or(equals(4).and(equals(5))).and(equals(6).negate());
}

Remember — only Java 8 onwards!

like image 182
Manuel Vera Silvestre Avatar answered Oct 21 '22 02:10

Manuel Vera Silvestre