JFS
JFS

Reputation: 3152

DDMathParser implicit multiplication not working

I use DDMathParser to solver formula expressions using Swift. The following code works fine, however, implicit multiplication doesn't. Reading the docs it should work... So, what do I miss here? my code:

...
substitutions.updateValue(3, forKey: "x")
let myString = "3$x"

    do{
        let expression = try Expression(string: myString, operatorSet: operatorSet, options: myTRO, locale: myLocale)
        let result = try evaluator.evaluate(expression, substitutions: substitutions)
        print("expression is: \(expression), the result is : \(result)")
    } catch {
        print("Error")
    }
...

The code throws the "Error". Using the string "3*$x" the expression is calculated as expected.

Upvotes: 0

Views: 207

Answers (2)

JFS
JFS

Reputation: 3152

Ok, got it myself. As Dave DeLong mentioned .allowImplicitMultiplication is included by default in the options but will get ignored when creating custom options. Since I want to use localized expressions (decimal separator within expression string is local) I need to use the advanced definition of Expression:

let expression = try Expression(string: ..., operatorSet: ..., options: ..., locale: ...)

In order to use the localized string option I defined let myLocale = NSLocale.current but accidentally also created a new operatorSet new options and passed it to the expression definition. The right way is not to create custom operatorSet and options but to use the defaults within the Expression definition:

let expression = try Expression(string: expressionString, operatorSet: OperatorSet.default, options: TokenResolverOptions.default, locale: myLocale)

Dave DeLong did a really great job in creating the DDMatParser framework. For newbies it is very hard to get started with. The wiki section at DDMathParser is pretty basic and doesn't give some details or examples for all the other great functionality DDMatParser is providing.

Upvotes: 0

Dave DeLong
Dave DeLong

Reputation: 243156

DDMathParser author here.

So, the .invalidFormat error is thrown when the framework has a sequence of tokens and is looking for an operator in order to figure out what goes around it. If it can't find an operator but still has tokens to resolve but no operator, then it throws the .invalidFormat error.

This implies that you have a 3.0 number token and a $x variable token, but no × multiplication token.

I see also that you're passing in a custom set of TokenResolverOptions (the myTRO variable). I'd guess that you're passing in an option set that does not include the .allowImplicitMultiplication value. If I try to parse 3$x without the .allowImplicitMultiplication resolver option, then I get the .invalidFormat error thrown.

Upvotes: 1

Related Questions