46 lines
1.6 KiB
C#
46 lines
1.6 KiB
C#
namespace Bts.ArithmeticExpressions;
|
|
|
|
using System.Numerics;
|
|
|
|
public class Difference : IArithmeticExpression<double> {
|
|
readonly IArithmeticExpression lhs;
|
|
readonly IArithmeticExpression rhs;
|
|
|
|
public Difference(IArithmeticExpression lhs, IArithmeticExpression rhs) {
|
|
this.lhs = lhs;
|
|
this.rhs = rhs;
|
|
}
|
|
|
|
public static Difference<T, T, T> Create<T>(
|
|
IArithmeticExpression<T> left, IArithmeticExpression<T> right)
|
|
where T : INumber<T>, ISubtractionOperators<T, T, T> =>
|
|
new(left, right);
|
|
|
|
public double Evaluate(IDictionary<string, object?> env) =>
|
|
evaluateArg(lhs, nameof(lhs), env) - evaluateArg(rhs, nameof(rhs), env);
|
|
|
|
static double evaluateArg(
|
|
IArithmeticExpression expr, string name, IDictionary<string, object?> env) {
|
|
var obj = expr.Evaluate(env);
|
|
return ConvertUtils.try_convert(expr.Evaluate(env), out double dbl) ? dbl :
|
|
throw new Exception(
|
|
$"Invalid Difference. {name} is of type {obj?.GetType()} (expected {typeof(double)})");
|
|
}
|
|
}
|
|
|
|
public class Difference<TLeft, TRight, TResult> : IArithmeticExpression<TResult>
|
|
where TLeft : INumber<TLeft>, ISubtractionOperators<TLeft, TRight, TResult>
|
|
where TRight : INumber<TRight>
|
|
where TResult : INumber<TResult> {
|
|
readonly IArithmeticExpression<TLeft> left;
|
|
readonly IArithmeticExpression<TRight> right;
|
|
|
|
public Difference(IArithmeticExpression<TLeft> left, IArithmeticExpression<TRight> right) {
|
|
this.left = left;
|
|
this.right = right;
|
|
}
|
|
|
|
public TResult Evaluate(IDictionary<string, object?> env) =>
|
|
left.Evaluate(env) - right.Evaluate(env);
|
|
}
|