added binary expressions

This commit is contained in:
2018-05-07 11:42:25 +02:00
parent 3ce0505f4e
commit dcaf7f0775
2 changed files with 47 additions and 12 deletions

View File

@@ -1,12 +1,20 @@
package worms.programs;
public abstract class BinaryExpression<L, R> implements Expression {
import java.util.function.BinaryOperator;
import java.util.function.DoubleBinaryOperator;
protected final L left;
protected final R right;
public abstract class BinaryExpression implements Expression {
public BinaryExpression(L left, R right) {
protected final Object left;
protected final Object right;
public BinaryExpression(Object left, Object right) {
this.left = left;
this.right = right;
}
@SuppressWarnings("unchecked")
protected Object execute(BinaryOperator op) {
return op.apply(this.left, this.right);
}
}

View File

@@ -1,5 +1,6 @@
package worms.programs;
import com.sun.org.apache.xpath.internal.operations.Bool;
import worms.model.Program;
import worms.util.ModelException;
import worms.util.MustNotImplementException;
@@ -251,14 +252,16 @@ public class ProgramFactory implements IProgramFactory {
@Override
public Object createAdditionExpression(Object left, Object right, SourceLocation location) throws ModelException {
Expression addition = new BinaryExpression<>(left, right) {
if (!(left instanceof Double && right instanceof Double)) {
throw new IllegalArgumentException();
}
return new BinaryExpression(left, right) {
@Override
public Object execute() {
return this.left + this.right;
public Double execute() {
return (double) execute((l,r) -> (double) l + (double) r);
}
};
return new Program();
}
/**
@@ -271,7 +274,16 @@ public class ProgramFactory implements IProgramFactory {
*/
@Override
public Object createAndExpression(Object left, Object right, SourceLocation sourceLocation) throws ModelException {
return null;
if (!(left instanceof Boolean && right instanceof Boolean)) {
throw new IllegalArgumentException();
}
return new BinaryExpression(left, right) {
@Override
public Boolean execute() {
return (boolean) execute((l,r) -> (boolean) left && (boolean) right);
}
};
}
/**
@@ -297,7 +309,13 @@ public class ProgramFactory implements IProgramFactory {
*/
@Override
public Object createEqualityExpression(Object left, Object right, SourceLocation location) throws ModelException {
return null;
return new BinaryExpression(left, right) {
@Override
public Boolean execute() {
return (boolean) execute((l,r) -> left.equals(right));
}
};
}
/**
@@ -311,7 +329,16 @@ public class ProgramFactory implements IProgramFactory {
*/
@Override
public Object createLessThanExpression(Object left, Object right, SourceLocation location) {
return null;
if (!(left instanceof Double && right instanceof Double)) {
throw new IllegalArgumentException();
}
return new BinaryExpression(left, right) {
@Override
public Boolean execute() {
return (boolean) execute((l,r) -> (double) left < (double) right);
}
};
}
@Override