78 lines
2.3 KiB
Objective-C
78 lines
2.3 KiB
Objective-C
//
|
|
// MPSumFunction.m
|
|
// MathPad
|
|
//
|
|
// Created by Kim Wittenburg on 22.04.14.
|
|
// Copyright (c) 2014 Kim Wittenburg. All rights reserved.
|
|
//
|
|
|
|
#import "MPSumFunction.h"
|
|
|
|
#import "MPExpression.h"
|
|
#import "MPExpressionTree.h"
|
|
#import "MPEvaluationContext.h"
|
|
|
|
@implementation MPSumFunction
|
|
|
|
MPFunctionAccessorImplementation(StartExpression, _startExpression)
|
|
MPFunctionAccessorImplementation(TargetExpression, _targetExpression)
|
|
MPFunctionAccessorImplementation(SumExpression, _sumExpression)
|
|
|
|
- (NSArray *)childrenAccessors
|
|
{
|
|
return @[@"startExpression", @"targetExpression", @"sumExpression"];
|
|
}
|
|
|
|
#pragma mark Evaluating Functions
|
|
|
|
- (BOOL)validate:(NSError *__autoreleasing *)error
|
|
{
|
|
MPExpressionTree *startTree = [self.startExpression parse];
|
|
if (![startTree validateExpectingVariableDefinition:YES error:error]) {
|
|
return NO;
|
|
}
|
|
|
|
MPExpressionTree *targetTree = [self.targetExpression parse];
|
|
if (![targetTree validate:error]) {
|
|
return NO;
|
|
}
|
|
|
|
[[MPEvaluationContext sharedContext] push];
|
|
[[MPEvaluationContext sharedContext] defineVariable:startTree.definedVariable withValue:[NSDecimalNumber notANumber]];
|
|
MPExpressionTree *sumTree = [self.sumExpression parse];
|
|
if (![sumTree validate:error]) {
|
|
return NO;
|
|
}
|
|
[[MPEvaluationContext sharedContext] pop];
|
|
return YES;
|
|
}
|
|
|
|
- (NSDecimalNumber *)evaluate
|
|
{
|
|
MPExpressionTree *startTree = [self.startExpression parse];
|
|
NSDecimalNumber *start = [startTree evaluate];
|
|
NSDecimalNumber *target = [[self.targetExpression parse] evaluate];
|
|
MPExpressionTree *sumTree = [self.sumExpression parse];
|
|
|
|
NSDecimalNumber *value = [NSDecimalNumber zero];
|
|
|
|
[[MPEvaluationContext sharedContext] push];
|
|
for (NSDecimalNumber *current = start;
|
|
[current compare:target] <= 0;
|
|
current = [current decimalNumberByAdding:[[NSDecimalNumber alloc] initWithInteger:1]]) {
|
|
[[MPEvaluationContext sharedContext] defineVariable:startTree.definedVariable withValue:current];
|
|
value = [value decimalNumberByAdding:[sumTree evaluate]];
|
|
}
|
|
[[MPEvaluationContext sharedContext] pop];
|
|
return value;
|
|
}
|
|
|
|
#pragma mark Working With Functions
|
|
|
|
- (NSString *)description
|
|
{
|
|
return [NSString stringWithFormat:@"Sum(From: %@; To: %@; Using: %@)", self.startExpression, self.targetExpression, self.sumExpression];
|
|
}
|
|
|
|
@end
|