public static EvaluationResult Sum(EvaluationResult numbers) { if (numbers == null) { throw new ArgumentNullException(nameof(numbers)); } if (numbers.Type != EvaluationType.Enumerable) { throw new Exception("Sum expects a list of numerics"); } var list = numbers.AsList(); if (list.Any(n => n.Type != EvaluationType.Int && n.Type != EvaluationType.Float)) { throw new Exception("Sum expects a list of numerics"); } float sum = 0; foreach (var n in list) { sum += n.AsFloat().Value; } return(sum); }
public void CanUseBasicFunctions() { EvaluationResult value = null; //miss out time trial for the first eval, as this includes the start-up time for the interpreter etc value = EvaluateOperation(@"SumInts([three], 2, 1)", NumericPrecision.Decimal, new Dictionary <string, object> { { "[three]", 3 } }, new Dictionary <string, ExternalFunction> { { "SumInts", SumInts } }); Assert.AreEqual(EvaluationType.Int, value.Type); Assert.AreEqual(6, value.AsInt().Value); using (var timer = new TimeAssertion(milliseconds: 5)) { value = EvaluateOperation(@"SumInts([three], 2) + 1", NumericPrecision.Decimal, new Dictionary <string, object> { { "[three]", 3 } }, new Dictionary <string, ExternalFunction> { { "SumInts", SumInts } }); Assert.AreEqual(EvaluationType.Int, value.Type); Assert.AreEqual(6, value.AsInt().Value); } using (var timer = new TimeAssertion(milliseconds: 5)) { value = EvaluateOperation(@"SumInts([three], ((2 + 4) * 2) / 2) + 1", NumericPrecision.Decimal, new Dictionary <string, object> { { "[three]", 3 } }, new Dictionary <string, ExternalFunction> { { "SumInts", SumInts } }); Assert.AreEqual(EvaluationType.Int, value.Type); Assert.AreEqual(10, value.AsInt().Value); } using (var timer = new TimeAssertion(milliseconds: 5)) { value = EvaluateOperation(@"ListFactory()", NumericPrecision.Decimal, null, new Dictionary <string, ExternalFunction> { { "ListFactory", ListFactory } }); Assert.AreEqual(EvaluationType.Enumerable, value.Type); Assert.IsTrue(value.AsList().Select(i => i.Result).SequenceEqual(new List <object> { 1, 2, 3 })); } using (var timer = new TimeAssertion(milliseconds: 5)) { value = EvaluateOperation(@"IncrementInt(1)", NumericPrecision.Decimal, null, new Dictionary <string, ExternalFunction> { { "IncrementInt", IncrementInt } }); Assert.AreEqual(EvaluationType.Int, value.Type); Assert.AreEqual(2, value.AsInt().Value); } using (var timer = new TimeAssertion(milliseconds: 10)) { value = EvaluateOperation(@"ExpressionFactoryResultingInTwo()", NumericPrecision.Decimal, new Dictionary <string, object> { { "[two]", 2 } }, new Dictionary <string, ExternalFunction> { { "ExpressionFactoryResultingInTwo", ExpressionFactoryResultingInTwo } }); Assert.AreEqual(EvaluationType.Int, value.Type); Assert.AreEqual(2, value.AsInt().Value); } }