By default, all binary operators are left associative. That means if you give a string, such as
@"1 - 2 - 3", it will be parsed as
@"(1 - 2) - 3.
The exception to this is the power operator (
**), which has its associativity determined at runtime. The reason for this is that the power operator is supposed to be right associative, but is interpreted by
NSPredicate as left associative (rdar://problem/8692313).
DDParser performs a test to match the associativity used by
If you want this operator (or any binary operator) to be parsed with specific associativity, you can do so like this:
DDParser *parser = [DDParser parserWithString:@"2 ** 3 ** 2"]; [parser setPowerAssociativity:DDOperatorAssociativityRight]; NSError *error = nil; DDExpression *e = [parser parsedExpressionWithError:&error];
Most binary operators can have their associativity changed this way. If you want to change the associativity of an operator for all future parsings, you can use the class methods on
DDParser to do so. For example:
NSLog(@"%@", [@"1 - 2 - 3" numberByEvaluatingString]); //logs -4 [DDParser setDefaultAdditionAssociativity:DDOperatorAssociativityRight]; NSLog(@"%@", [@"1 - 2 - 3" numberByEvaluatingString]); //logs 2
Changing the default associativity only affects parsers instantiated after the change. It does not affect existing parsers.