0

I want read in mathematical functions and interpret them. So far I worked with binary expressions and used the Infix to Prefix Method to read my string (e.g. 4*3+1).

However, meanwhile I want to read in also more complex expressions that are not translatable into a binary tree.

Some Examples:

  1. max(x_1,x_2,x_3,x_4,x_5) + max(y_1,y_2)
  2. round(interpolate(x_1,x,y),2)
  3. customfunction(x,y,z) + 4

I have some problems to find a way to translate the given string into a non-binary tree. How would be a good way to do this, are there some known methods? Since I need to support some own custom functions I can not use any existing library.

I don't expect any code, I'm interested in the theory doing this.

2 Answers2

0

Normally you'll need to define a grammar (a very simple one in this case) that defines what are the rules for parsing your text, and then generate a parser that is based on this grammar through one of the various libraries that exist. For a grammar so simple Antlr is surely overblown. There is a serie of articles here about writing a "Writing a Recursive Descent Parser" or if you search for peg (a family of grammar parsers) on nuget you'll find plenty of implementations.

Note that this branch of computer science is quite vast... You can start from here lexers vs parsers for the theoretical part.

xanatos
  • 109,618
  • 12
  • 197
  • 280
0

Look at your custom non-binary functions the same way as you look at the binary expressions.

E.g. 2+3*4 translates to +(*(3,4),2) // + and * here are just function names

You can mix in a custom function:

E.g. a^3 + Max(a,b,c)*2 translates to: +(^(a,3), *(2, Max(a,b,c))

In your interpreter define what +(), ^(), Max(), your_custom_function() mean and what parameters (i.e. child nodes to in the tree) to expect. The tree will not be binary, but that does not really change how you create it and traverse it.

Eriks Klotins
  • 4,042
  • 1
  • 12
  • 26