How to get arithmetical operators at runtime? - java

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
}

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.

public class Calculator {
public static enum Operation {ADD, MUL, SUB, DIV};
private int x; // store value from previous operations
public void calculate(int x, Operation operation) {
switch(operation) {
case ADD:
this.x += x;
break;
case MUL:
this.x *= x;
break;
case SUB:
this.x -= x;
break;
case DIV:
this.x /= x;
break;
}
}
public int getResult() {
return this.x;
}
}
To use it elsewhere in your code:
public static void main(String[] args) {
Calculator c = new Calculator();
c.calculate(4, Calculator.Operation.ADD);
// Other operations
c.getResult(); // get final result
}

Assuming you are trying to just add and multiply x, just do the following:
public int calculate(int x, String str) {
// while(true) is gonna get you into some trouble
if( str.equals("ADD")) {
return x + x;
}
else if( str.equals("MUL")) {
return x * x;
}
else
return x; // not sure what you want to do in this case
}

Related

decorator design pattern for adding new methods and codes to the existing object

I am new in design patterns. I am trying to use decorator design pattern to add new codes and functionalities to my existing app.
Suppose I have a class of App which has two methods "Add" and "Multiply". At some point (run time) the app will require to calculate the average as well.
So, I am trying to use decorator design pattern to make this possible.
So far I have :
public class App implements Code{
public int a=2;
public int b=3;
#Override
public int Add(int a, int b) {
int add;
add = a+b;
return add;
}
#Override
public int Multiply(int a, int b) {
int mul;
mul= a*b;
return mul;
}
}
In order to do this I define an interface "Code" like this:
public interface Code {
public int Add (int a, int b);
public int Multiply (int a, int b);
}
and then a decorator abstract class CodeExtention
public abstract class CodeExtention implements Code{
protected Code extendedCode;
public CodeExtention(Code extendedCode) {
this.extendedCode = extendedCode;
}
#Override
public int Multiply(int a, int b){
return extendedCode.Multiply(a, b);
}
#Override
public int Add(int a, int b){
return extendedCode.Add(a, b);
}
}
Now I define a concert class "AVG" extended from my abstract class like this :
public class AVG extends CodeExtention{
public AVG(Code extendedCode) {
super(extendedCode);
}
public int AVGcalculator (int a, int b){
return (a+b)/2;
}
#Override
public int Add(int a, int b) {
return super.Add(a, b);
}
#Override
public int Multiply(int a, int b) {
return super.Multiply(a, b);
}
}
Now I expect that my app can calculate the average to do so I have in my main :
public static void main(String[] args) {
Code app = new App();
app = new AVG(app);
}
}
Here I can have :
System.out.println(app.Add(3, 4));
System.out.println(app.Multiply(3, 4));
I still cannot have:
System.out.println(app.AVGcalculator(3, 4));
I don't know what is wrong, or even if I can use this design pattern for my scenario!
The decorator pattern is a really bad choice for this.
The decorator fulfills the same contract — the same API — as the decorated object. What you want is to change the contract. Thus, the pattern isn't applicable (read this for a good example when to use a decorator).
What you can do is using the Command pattern:
interface BinaryIntOperation {
int execute(int a, int b);
}
class AddOperation implements BinaryIntOperation {
int execute(int a, int b) {
return a + b;
}
}
class MultiplyOperation implements BinaryIntOperation {
int execute(int a, int b) {
return a * b;
}
}
class AverageOperation implements BinaryIntOperation {
int execute(int a, int b) {
return (a + b)/2;
}
}
You can then do many thing from there:
BinaryIntOperation op = new AddOperation();
System.out.println(op.execute(3, 4));
op = new MultiplyOperation();
System.out.println(op.execute(4, 5));
You can also write things like that:
public int[] execute(int[] arr, BinaryIntOperation op, int a) {
for (int i = 0; i < arr.length; i++)
arr[i] = op.execute(a, arr[i]);
return arr;
}
The command pattern is a behavioral pattern, which seems more like what you want (changing behavior).
Note that in C#, you could do exactly what you want by using extension methods. But Java doesn't have those.
The app is of type Code since AVGcalculator is not part of Code interface you cannot call it if you want to call for AVGcalculator you can do it like this
System.out.println(((AVG)app).AVGcalculator(3, 4));

Composing Function interfaces in Java

interface PairFloatFunction {
Pair<Float,Float> calculate(int x);
}
interface FloatFunction {
float calculate(int x);
}
class SQRT implements PairFloatFunction {
public Pair<Float, Float> calculate(int x) {
return new Pair(-pow(x,0.5), pow(x,0.5))
}
}
class ADD_ONE implements FloatFunction {
public Float calculate(int x) {
return x + 1;
}
}
I would like to compose to functions so that I can perfom this:
ADD_ONE(SQRT(100)) = Pair(-9,11)
I understand i need to 'glue' the functions together.
but I am stuck here, should I be writing another method overload that does this?
class ADD_ONE {
public Float calculate(int x) {
return x + 1;
}
public Float calculate(Pair pair) {
pair.first += 1;
pair.second += 1;
return pair
}
}
Sorry I am new to functional programming, is there a nice solution to this?
Based on your code above, I would create a generic interface which will be responsible for calculating.
interface Calculation<T> {
T calculate(int x);
}
This is a Java 7 implementation, because you did not specify Java 8.
Further Explanation
The return type T is generic; meaning that your implementation can return any Object type but it must consume an integer x. You could even make the x parameter generic so that you can decide what function will take as a parameter type.
Note: The static classes would be moved into their own class files and the static modifier should be removed. I only did this to consolidate everything for the sake of brevity.
Full Example
public class Functional {
static interface Calculation<T> {
T calculate(int x);
}
static class Sqrt implements Calculation<Pair<Float, Float>> {
public Pair<Float, Float> calculate(int x) {
float root = (float) Math.pow(x, 0.5);
return new Pair<Float, Float>(-root, +root);
}
}
static class AddOne implements Calculation<Float> {
public Float calculate(int x) {
return (float) (x + 1);
}
}
static <T> T calculate(int x, Calculation<T> calculation) {
return calculation.calculate(x);
}
public static void main(String[] args) {
Calculation<?>[] calculations = { new Sqrt(), new AddOne() };
int x = 49;
for (Calculation<?> calculation : calculations) {
System.out.printf("%s: %s%n",
calculation.getClass().getSimpleName(),
calculate(x, calculation));
}
}
static class Pair<T, U> {
private T val1;
private U val2;
public Pair(T val1, U val2) {
this.val1 = val1;
this.val2 = val2;
}
protected T getVal1() {
return val1;
}
protected void setVal1(T val1) {
this.val1 = val1;
}
protected U getVal2() {
return val2;
}
protected void setVal2(U val2) {
this.val2 = val2;
}
#Override
public String toString() {
return "(" + val1 + ", " + val2 + ")";
}
}
}
Output
Sqrt: (-7.0, 7.0)
AddOne: 50.0

Java consecutive method calls

So I've seen, in many places, calling methods of a class like:
SomeClass obj = new SomeClass();
obj.addX(3).addY(4).setSomething("something").execute();
I don't think I completely understand how that works. Is each method independent of each other, so the above is equal to:
obj.addX(3);
obj.addY(4);
obj.addSomething("something");
obj.execute();
Or are they designing their class structure in some other fashion that allows for this. If they are how are they designing their classes to support this?
Also, does that have a specific name? Or is this just calling methods on a class?
That would be method chaining. It can do one of two things.
Each call to a method returns this which allows you to continue to call methods on the original instance.
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass addX(int n)
{
_x += n;
return this;
}
public SomeClass addY(int n)
{
_y += n;
return this;
}
public SomeClass setSomething(String something)
{
_something = something;
return this;
}
// And so on, and so on, and so on...
}
Each method call returns a new instance of the class with everything copied/updated appropriately. This makes the class immutable (so you don't accidentally modify something that you didn't mean to).
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass(int x, int y, String something)
{
_x = x;
_y = y;
_something = something;
}
public SomeClass addX(int n)
{
return new SomeClass(_x + n, _y, _something);
}
public SomeClass addY(int n)
{
return new SomeClass(_x, _y + n, _something);
}
public SomeClass setSomething(String something)
{
return new SomeClass(_x, _y, something);
}
// And so on, and so on, and so on...
}
Some people have also mentioned Fluent Interfaces. Fluent Interfaces utilize method chaining to create an API that provides something along the lines of a Domain Specific Language which can make code read much more clearly. In this case, your example doesn't quite qualify.
they modify object's state and return the same object back mostly
class Number{
int num;
public Number add(int number){
num+=number;
return this;
}
}
you can call it like
new Number().add(1).add(2);
most of the time the use case is to return new Object to support immutability
Each of those methods return an instance. For example, the call to
obj.addX(3)
will return the same instance obj, so the call
obj.addX(3).addY(4)
will be equivalent to
obj.addY(4)
This is called method chaining.
The methods are implemented like this:
public SomeClass addX(int i) {
// ...
return this; // returns the same instance
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 abc = new Test1();
abc.add1(10, 20).sub1(40, 30).mul1(23, 12).div1(12, 4);
}
public Test1 add1(int a, int b)
{
int c = a + b;
System.out.println("Freaking Addition output : "+c);
return this;
}
public Test1 sub1(int a, int b)
{
int c = a - b;
System.out.println("Freaking subtraction output : "+c);
return this;
}
public Test1 mul1(int a, int b)
{
int c = a * b;
System.out.println("Freaking multiplication output : "+c);
return this;
}
public Test1 div1(int a, int b)
{
int c = a / b;
System.out.println("Freaking divison output : "+c);
return this;
}
}

How to make a function inside a class mutuable?

Imagine I have a class
class A {
int a;
int b;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
return 0;
}
void setTheFunction([...]) {
[...]
}
}
And for every new object I instantiate, I want to be able to define theFunction() in a new way by calling setTheFunction( [...] ). For example, I want to do something like this:
A test = new A(3,2);
test.setTheFunction ( int x = a*b; return x*x+2; );
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
Or something like this:
A test2 = new A(1,5);
test.setTheFunction ( for(int i=0; i<b; i++) a=a*b*i; return a; );
Now, what I could of course do is write all of those functions inside class A and use a switch statement to determine which one is to pick. But if I don't want the algorithm of theFunction() hardcoded inside my class A, is there any way to do something similar to the above? And what would setTheFunction() look like? What type of argument would you have to pass?
You can use Callable.
public class A<V> {
public int a;
public int b;
private Callable<V> callable;
public A(int a, int b) {
this.a = a;
this.b = b;
}
public V theFunction() {
try {
return callable.call();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void setTheFunction(Callable<V> callable) {
this.callable = callable;
}
}
Then, to use it:
final A<Integer> test = new A<Integer>(3, 2);
test.setTheFunction(new Callable<Integer>() {
int x = test.a * test.b;
return x * x + 2;
});
System.out.println(test.theFunction());
Of course, the generic typing of A isn't necessary, but I've added it to make this answer to be less restricted.
If you always need to operate on the same arguments, you could solve this by defining an interface such as:
public interface MethodPerformer {
int performOperation(int a, int b);
}
Then pass in implementations of this to your setTheFunction method. Finally, invoke the operation when you call the other method:
class A {
int a;
int b;
MethodPerformer performer;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
performer.performOperation(a, b);
}
void setTheFunction(MethodPerformer performer) {
this.performer = performer;
}
}
Clearly additional code would be required to check the performer is not null. Perhaps take a performer in the constructor?
Instead of using a setter, the more natural way is to use an anonymous sub-class. This way the compiler will check it behaves correctly and has access to the right variables.
public class Main {
static abstract class A {
protected int a, b;
A(int a, int b) {
this.a = a;
this.b = b;
}
public abstract int theFunction();
}
public static void main(String... ignored) {
A test = new A(3, 2) {
#Override
public int theFunction() {
int x = a * b;
return x * x + 2;
}
};
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
A test2 = new A(1, 5) {
#Override
public int theFunction() {
for (int i = 1; i < b; i++) a = a * b * i;
return a;
}
};
System.out.println(test2.theFunction());
}
}
prints
38
15000
With this you can solve any kind of problem, that involves any kind of public variable of A (but can work with package private variables as well, if the AFunction implementation resides in the same package), that a function may use to perform it's operation. It's just not as compact as it can be in other languages than java.
interface AFunction
{
int call(A a);
}
class A
{
int a;
int b;
//giving it a default implementation
private AFunction f = new AFunction()
{
#Override
public int call(A a)
{
return a.a * a.b;
}
};
A(int a, int b)
{
this.a = a;
this.b = b;
}
int theFunction()
{
return f.call(this);
}
void setTheFunction(AFunction f)
{
this.f = f;
}
}
By the way as AlexTheo points out, all answers so far (except for Peter Lawrey's) are a form of the strategy design pattern.
The easiest way to do this is defining "A" as an interface instead of a class. You declare theFunction() without actually implementing it.
In client code, everytime you need "A", you instantiate a so-called anonymous inner class.
For example:
new A() { #Override public int theFunction() { ...your implementation... } };

java generic addition

I'm attempting implement the add method mentioned in the Generic sparse matrix addition question
class Matrix<T extends Number>
{
private T add(T left, T right)
{
if (left instanceof Integer)
{
return new Integer(((Integer)left).intValue() + ((Integer)right).intValue());
}
}
The compiler errors with found java.lang.Integer Required T at the line where I return a new Integer. I'm not sure what I'm missing since T extends Number and Integer is a subclass of Number.
The compiler doesn't let you do this because T might be some other class, such as Double.
You know that T is Integer from the instanceof check, but the compiler doesn't.
Java's type system is simply not capable of expressing this. Here is a work around.
Create an interface Numeric that provides the numeric operations you are interested in, and write its implementations for the data types you are interested in.
interface Numeric<N> {
public N add(N n1, N n2);
public N subtract(N n1, N n2);
// etc.
}
class IntNumeric extends Numeric<Integer> {
public static final Numeric<Integer> INSTANCE = new IntNumeric();
private IntNumeric() {
}
public Integer add(Integer a, Integer b) {
return a + b;
}
public Integer subtract(Integer a, Integer b) {
return a - b;
}
// etc.
}
And rewrite your Matrix class constructor to accept this implementation.
class Matrix<N> {
private final Numeric<N> num;
private final List<List<N>> contents;
public Matrix(Numeric<N> num) {
this.num = num;
this.contents = /* Initialization code */;
}
public Matrix<N> add(Matrix<N> that) {
Matrix<N> out = new Matrix<N>(num);
for( ... ) {
for( ... ) {
out.contents.get(i).set(j,
num.add(
this.contents.get(i).get(j),
that.contents.get(i).get(j),
)
);
}
}
return out;
}
}
// Use site
Matrix<Integer> m = new Matrix<Integer>(IntNumeric.INSTANCE);
Hope that helps.
"I'm not sure what I'm missing since T extends Number and Integer is a subclass of Number."
This statement is false. In general if you have:
public class B extends A {
}
public class C extends A {
}
it does not mean that B can be cast to C. So writing something like:
public <T extends A> T method(T arg) {
return (B)arg;
}
and you calling it with B b = (B)method(C); is obviously wrong.
package generics;
public class Box<T> {
public T j,k;
int l;
float f;
#SuppressWarnings("unchecked")
public void add(T j,T k) {
this.j = j;
this.k=k;
if(j.toString().contains("."))
{
this.f=Float.parseFloat(j.toString())+Float.parseFloat(k.toString());
} else{
this.l=Integer.parseInt(j.toString())+Integer.parseInt(k.toString());
}
}
public int getInt() {
return l;
}
public float getFloat() {
return f;
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<Float> floatBox = new Box<Float>();
integerBox.add(new Integer(10),new Integer(20));
floatBox.add(new Float(2.2),new Float(3.3));
System.out.printf("Integer Value :%d\n\n", integerBox.getInt());
System.out.printf("float Value :%f\n", floatBox.getFloat());
}
}

Categories

Resources