All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.bpodgursky.jbool_expressions.rules.SimplifyOr Maven / Gradle / Ivy

There is a newer version: 8.1.2
Show newest version
package com.bpodgursky.jbool_expressions.rules;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.bpodgursky.jbool_expressions.*;

import java.util.*;

public class SimplifyOr extends Rule, K> {

  @Override
  public Expression applyInternal(Or input) {

    for (Expression expr : input.expressions) {
      if (expr instanceof Literal) {
        Literal l = (Literal) expr;

        //  ignore anything that is "false"
        if (!l.getValue()) {
          return copyWithoutFalse(input);
        } else {
          return Literal.of(true);
        }
      }

      //  succeed immediately if require something or its opposite
      if( expr instanceof Not){
        Expression notChild = ((Not)expr).getE();
        for(Expression child: input.expressions){
          if(child.equals(notChild)){
            return Literal.getTrue();
          }
        }
      }
    }

    return input;
  }

  private Expression copyWithoutFalse(Or input){
    List> copy = Lists.newArrayList();
    for (Expression expr : input.expressions) {
      if (expr instanceof Literal) {
        Literal l = (Literal) expr;

        //  ignore anything that is "false"
        if (!l.getValue()) {
          continue;
        }
      }
      copy.add(expr);
    }

    if (copy.isEmpty()) {
      return Literal.of(false);
    }

    return Or.of(copy);
  }

  @Override
  protected boolean isApply(Expression input) {
    return input instanceof Or;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy