Parser

public class Parser

The Parser converts a mathematical expression to a tree.

As humans, we read and write math as a line of text. If you were to type a math expression, it would probably look something like this:

(1 + 2) - abs(-3) * x²

You could also just look at that math expression and use your intuition to prioritize where to start simplifying. But a computer will understand the expression best when it’s stored in a tree. These trees can be surprisingly complicated — even a short expression like (1 + 2) - abs(-3) * x² becomes this tree:

          (-)
         /   \
        ( )   (*)
       /     /   \
     (+)    abs   (^)
    /   \    |   /   \
   1     2  -3  x     2
  • Makes the difference between regular math equations and tables (excel like) formulas.

    See more

    Declaration

    Swift

    public enum ParseContext
  • Initialize Parser with a mathematical expression as a String ( ASCIIMath)

    Declaration

    Swift

    public init(_ str: String, type: ParseContext = .math, tablesContext: Tables? = nil)

    Parameters

    str

    ASCIIMath expression

    type

    The mode in which the parser should be executed. Can be 2 options: math (for standard math expression) and tables (for excel like expression)

    tablesContext

    If the type is set to tables, then a Tables object is required to interact with the different cells

  • This function will be in charge of parsing the expression.

    After, initializing the Parser, use this function to get an ExpressionNode (aka expression tree). Here is a code example:

    let p = Parser("5.0 - sqrt(8) * 5 = x^2 - factorial(4)")
    let expression = try p.parse()
    

    Declaration

    Swift

    public func parse() throws -> ExpressionNode
  • Initialize Parser with \LaTeX

    Declaration

    Swift

    convenience init(latex: String)