VBMathParser is a library for mathematical expressions parsing.
It uses ARC. DO NOT FORGET to turn on ARC for framework's sources (-fobjc-arc flag), if your project is developed in non-ARC environment.
Drag VBMathParser dir into your project.
OR
use Cocoapods (is coming in several days)
This library if DI-ready.
Create an instance of VBMathParser using method
- (nullable instancetype) initWithLexicalAnalyzer:(nonnull id<VBMathParserLexicalAnalyzer>) lexicalAnalyzer
syntaxAnalyzer:(nonnull id<VBMathParserSyntaxAnalyzer>) syntaxAnalyzer
calculator:(nonnull id<VBMathParserCalculator>) calculator NS_DESIGNATED_INITIALIZER;
It needs three objects
-
lexical analyzer (conforms VBMathParserLexicalAnalyzer protocol) It breaks string expression into several tokens.
-
syntax analyzer (conforms VBMathParserSyntaxAnalyzer protocol) It checks the syntax of given expression (not openned or not closed brackets, etc.)
-
calculator (conforms VBMathParserCalculator protocol) Prepares given array of tokens for fast calculation and calculates the result.
Inject your own objects that conform to these protocols or use the default ones
- VBMathParserDefaultLexicalAnalyzer
- VBMathParserDefaultSyntaxAnalyzer
- VBMathParserDefaultRPNCalculator
To simplify the creation of a default math parser call
- (nullable instancetype) initWithDefaultAnalyzers;
It will use default analyzers.
self.parser = [[VBMathParser alloc] initWithDefaultAnalyzers];
[self.parser setExpression:@"......"];
OR
[self.parser setExpression:@"......"
withVariables:@[@"x", @"y", @"z", @"t"]];
double result = [self.parser evaluate];
OR
double result = [self.parser evaluateWithVariablesValues:@{@"x": @(1),
@"y": @(2),
@"z": @(3),
@"t": @(4)}];
You will get an exception if expression syntax has errors. To handle such cases you should you try/catch pattern.
-
If you open a bracket - do not forget to close it later.
-
All operations are expected to be used in mathematical expressions as binary operations.
Only "-" operation can be used both as binary and as unary one. Actually unary minus operation is always replaced by a binary one as the following:
"-4" -> "0-4"
"2 * (-4)" -> "2 * (0 - 4)"
"-abs(4)" -> "0 - abs(4)"
- All functions are expected to be followed by an argument enclosed in brackets.
abs3 - error!
abs(3) - OK
- Variable name must consist of at least one letter plus letters and numbers.
valid names: x, y, x1, x01, etc
invalid names: 0x, x_213, etc
- brackets: (, )
- operations: +, - (unary/binary), *, /, ^(power)
- functions: abs, sin, cos, tan
- variables
- constants: pi
Feel free to left a feature request
VBMathParser is available under the MIT license. See the LICENSE file for more info.