46 lines
1.6 KiB
C#
46 lines
1.6 KiB
C#
namespace Bts.ArithmeticExpressions;
|
|
|
|
using System.Numerics;
|
|
|
|
class Sum : IArithmeticExpression<double> {
|
|
readonly IArithmeticExpression left;
|
|
readonly IArithmeticExpression right;
|
|
|
|
public Sum(IArithmeticExpression left, IArithmeticExpression right) {
|
|
this.left = left;
|
|
this.right = right;
|
|
}
|
|
|
|
public static Sum<T, T, T> Create<T>(
|
|
IArithmeticExpression<T> left, IArithmeticExpression<T> right)
|
|
where T : INumber<T>, IAdditionOperators<T, T, T> =>
|
|
new(left, right);
|
|
|
|
public double Evaluate(IDictionary<string, object?> env) =>
|
|
evaluateArg(left, nameof(left), env) + evaluateArg(right, nameof(right), 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 Sum. {name} is of type {obj?.GetType()} (expected {typeof(double)})");
|
|
}
|
|
}
|
|
|
|
class Sum<TLeft, TRight, TResult> : IArithmeticExpression<TResult>
|
|
where TLeft : INumber<TLeft>, IAdditionOperators<TLeft, TRight, TResult>
|
|
where TRight : INumber<TRight>
|
|
where TResult : INumber<TResult> {
|
|
readonly IArithmeticExpression<TLeft> left;
|
|
readonly IArithmeticExpression<TRight> right;
|
|
|
|
public Sum(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);
|
|
}
|