Search code examples
iosobjective-cnumbersexpressionddmathparser

iOS DDMathParser get solving steps of math expression


I am building a some kind of calculator for iOS using DDMathParser. I would like to know how to separate an expression (NSString) like 3+3*4 (After parsing add(3,multiply(3,4))) into its individual steps:multiply(3,4) add(3,12). I would prefer that I get these in an NSArray or other relatively useful list object.

  • Example: add(3,multiply(3,4))
  • [1] multiply(3,4)
  • [2] add(3,12)
  • [3] 15

Solution

  • DDMathParser author here.

    This should be pretty straight forward. The parser can give you back the well-formed expression tree instead of just the numeric evaluation. With the expression tree, you'd do something like this:

    1. Find the deepest expression in the tree. This is the first thing that will be evaluated.
    2. Evaluate that expression manually
    3. Substitute the evaluation back in to the tree in place of the original expression
    4. Create a copy of the entire tree to refer to what it looked at this point.
    5. Repeat until there's nothing more to evaluate.