DDMathParser author here.
There are two things wrong, and one thing suboptimal.
- Wrong - You can't call this function "sum". "sum" is a built-in function, and built-in functions cannot be overridden.
- Wrong - The first parameter of your function is:
"2x"
. That's fine, except thatx
is being interpreted as a function, but inside your for loop you're treatingx
as if it were a variable. You either need to fundamentally alter how your function works, or use the form2 * $x
(or just2$x
) as the first parameter to your function. - Suboptimal - Instead of getting the
doubleValue
off the evaluated arguments, just get theintegerValue
instead and avoid the whole double-to-int conversion.
Here's how I'd clean up your function (although you should probably do a bit more in the way of filling in the error
out parameter):
[evaluator registerFunction:^DDExpression *(NSArray *args, NSDictionary *vars, DDMathEvaluator *eval, NSError *__autoreleasing *error) {
DDExpression *final = nil;
if ([args count] == 3) {
DDExpression *expr = [args objectAtIndex:0];
DDExpression *start = [args objectAtIndex:1];
DDExpression *end = [args objectAtIndex:2];
//get the start and end values
NSInteger startValue = [[eval evaluateExpression:start withSubstitutions:vars error:error] integerValue];
NSInteger endValue = [[eval evaluateExpression:end withSubstitutions:vars error:error] integerValue];
double sum = 0;
for (NSInteger i = startValue; i <= endValue; i++) {
NSDictionary *substitution = @{@"x": @(i)};
NSNumber *value = [eval evaluateExpression:expr withSubstitutions:substitution error:error];
sum += [value doubleValue];
}
final = [DDExpression numberExpressionWithNumber:@(sum)];
}
return final;
} forName:@"sum2"];
With this, you can do sum2(2*$x, 2, 4)
and it will evaluate to 18.