Search code examples
javaarithmetic-expressions

How to get arithmetical operators at runtime?


How I can get arithmetical operators at run-time in Java? Suppose if I have values

  • ADD it should add the number
  • MUL then it should multiply the number

For Example

  public calculate(int x, String str){
   while(str.equals("some value")){
     If( str.equals("ADD"))
        // it should return me something like x+
     if( str.equals("MUL"))
        it return me something like x*
    }
    if( str.equals("FINAL"))
        it should return me x+x*x

  }

Solution

  • What you need is not runtime metaprogramming, but first class functions.

    The following represent first class functions, with arity 1 and 2 respectively.

    abstract class UnaryFunction<A, B> {
      public abstract B apply(A a);
    }
    
    abstract class BinaryFunction<A, B, C> {
      public abstract C apply(A a, B b);
    }
    

    For the sake of simplicity, let's use specialized versions of above classes.

    abstract class UnaryOperation {
      public abstract int apply(int a);
    }
    
    abstract class BinaryOperation {
      public abstract int apply(int a, int b);
    }
    

    Now construct a dictionary of the required arithmetic operations.

    Map<String, BinaryOperation> ops = new HashMap<String, BinaryOperation>();
    ops.put("ADD", new BinaryOperation() {
      public int apply(int a, int b) {
        return a + b;
      }
    });
    ops.put("MUL", new BinaryOperation() {
      public int apply(int a, int b) {
        return a * b;
      }
    });
    // etc.
    

    Add a method that partially applies BinaryOperation on one parameter.

    abstract class BinaryOperation {
      public abstract int apply(int a, int b);
    
      public UnaryOperation partial(final int a) {
        return new UnaryOperation() {
          public int apply(int b) {
            return BinaryOperation.this.apply(a, b);
          }
        };
      }
    }
    

    Now we can write your calculate method.

    public UnaryOperation calculate(int x, String opString) {
      BinaryOperation op = ops.get(opString);
      if(op == null)
        throw new RuntimeException("Operation not found.");
      else
        return op.partial(x);
    }
    

    Use:

    UnaryOperation f = calculate(3, "ADD");
    f.apply(5); // returns 8
    
    UnaryOperation g = calculate(9, "MUL");
    f.apply(11); // returns 99
    

    The abstractions used in the above solution, namely first class function interfaces and partial application, are both available in this library.