示例#1
0
  /** 操作符重载,使用自定义解释器实现操作符重载 */
  public static void operatorOverload() {
    /*
     * 扩展Fel的+运算符,使其支持数组+数组
     */

    FelEngine fel = getEngine();
    // 单价
    double[] price = new double[] {2, 3, 4};
    // 费用
    double[] cost = new double[] {0.3, 0.3, 0.4};
    FelContext ctx = fel.getContext();
    ctx.set("单价", price);
    ctx.set("费用", cost);
    String exp = "单价+费用";
    Interpreters interpreters = new Interpreters();
    // 定义"+"操作符的解释方法。
    interpreters.add(
        "+",
        new Interpreter() {
          @Override
          public Object interpret(FelContext context, FelNode node) {
            List<FelNode> args = node.getChildren();
            double[] leftArg = (double[]) args.get(0).eval(context);
            double[] rightArg = (double[]) args.get(1).eval(context);
            return sum(leftArg) + sum(rightArg);
          }

          // 对数组进行求和
          public double sum(double[] array) {
            double d = 0;
            for (int i = 0; i < array.length; i++) {
              d += array[i];
            }
            return d;
          }
        });

    // 使用自定义解释器作为编译选项进行进行编译
    Expression expObj = fel.compile(exp, null, interpreters);
    Object eval = expObj.eval(ctx);
    System.out.println("数组相加:" + eval);
  }
示例#2
0
  /** 大数据量计算(计算1千万次) */
  public static void massData() {
    FelEngine fel = getEngine();
    final Interpreters opti = new Interpreters();
    final MutableInt index = new MutableInt(0);
    int count = 10 * 1000 * 1000;
    final double[] counts = new double[count];
    final double[] prices = new double[count];
    Arrays.fill(counts, 10d);
    Arrays.fill(prices, 2.5d);
    opti.add(
        "单价",
        new Interpreter() {
          @Override
          public Object interpret(FelContext context, FelNode node) {
            return prices[index.intValue()];
          }
        });
    opti.add(
        "数量",
        new Interpreter() {
          @Override
          public Object interpret(FelContext context, FelNode node) {
            return counts[index.intValue()];
          }
        });
    Expression expObj = fel.compile("单价*数量", null, opti);
    long start = System.currentTimeMillis();
    Object result = null;
    for (int i = 0; i < count; i++) {
      result = expObj.eval((FelContext) null);
      index.increment();
    }
    long end = System.currentTimeMillis();

    System.out.println("大数据量计算:" + result + ";耗时:" + (end - start));
  }