davedelong / DDMathParser

String → Number
MIT License
856 stars 153 forks source link

DDMathParser failing to tokenize solitary plus character #104

Closed joshdistler closed 9 years ago

joshdistler commented 9 years ago

Using DDMathStringTokenizer, while something like 2 + 4 tokenizes fine into 3 tokens (with the second being the + operator and the first and third being numbers), if I pass over a + alone, it fails to return it as a token.

This does not hold true for every other operator I've tried, such as / * - etc.

I can probably force this somehow but how can I get DDMathStringTokenizer to tokenize the + correctly?

To reproduce the issue: The following will return an array with no objects. If you change the string value to another operator character it will return a valid array.

NSError *error = nil; NSString *string = @"+"; DDMathOperatorSet *opSet = [DDMathOperatorSet defaultOperatorSet]; DDMathStringTokenizer *tokenizer = [[DDMathStringTokenizer alloc] initWithString:string operatorSet:opSet error:&error]; NSLog(@"Tokens:%@", [tokenizer allObjects]);

Note: This was originally posted here: http://stackoverflow.com/questions/30822751/ddmathparser-failing-to-tokenize-solitary-plus-character

davedelong commented 9 years ago

Interesting....

This is actually the tokenizer trying to be nice for you. When it sees +, it correctly identifies it as an operator, but since it's ambiguous (it could be unary or binary), it marks it as needing to be disambiguated.

Since this is the first token in the stream, the tokenizer correctly interprets it as a unary + operator.

However, the -[DDMathStringTokenizer _processToken:withError:] method drops all unary + operators on the floor, because they're pointless operators; they don't actually affect the evaluation of the result. Thus, it doesn't appear in the final array of tokens.

This should be better on the 1.1 branch, because there I separated the concepts of tokenizing and token interpretation, so on that branch the tokenizer will give you the + token, but it won't know that it's a unary + until after it passes through the token interpreter.

joshdistler commented 9 years ago

Yeah I was thinking the same (in comments on SO) that it was ambiguous so it decided to just return nil. Will the 1.1 branch make the tokenType property settable (to make forcing this one way or another easier)? I am already wrapping your tokens with my own but it would still be useful to simplify the wrapping.

davedelong commented 9 years ago

This is fixed on the 2.0 branch, which will be merged in to master soon.

joshdistler commented 9 years ago

Excellent! Thanks Dave.

On Aug 25, 2015, at 1:36 PM, Dave DeLong notifications@github.com wrote:

This is fixed on the 2.0 branch, which will be merged in to master soon.

— Reply to this email directly or view it on GitHub https://github.com/davedelong/DDMathParser/issues/104#issuecomment-134710967.