I’m new to Scala but I was wondering it it is possible to implement a simple Equation parser in the language.
Say I have a few functions (much like Excel functions):
IF(Cond a=b, val_true, val_false)
MID(String, Start_pos, num_chars) – string extract
LEN(String) – length of a string
OR(cond1, cond2, ... condn)
AND(cond1, cond2, ... condn)
So the idea would be I could pass in a formula at runtime as a string from a user as a command line argument along with any other params say IF(LEN(param1)=4,MID(param1,2,1), MID(param1,0,LEN(param1)))
The idea is to evaluate the function, so if the user provides that above formula and the string “scat” then the output would be “a”. If the string “scala” was given then the output would be “scala”…
How easy would this be to implement in Scala? What is the best design approach? I know there are no function pointers (in C I would have parsed the formula string into a collection of func points and gone from there)…
Any advice on how to approach this in efficient Scala style would be appreciated.
Cheers!
This question has motivated to experiment with combinator parsers. Given the following algebraic data types representing a subset of your expressions:
The following parser definition will parse your given expression and return a
Exprobject:Then parsing and evaluating the results can be done like this:
Note that the grammar I provided is just the minimum to make your example parse and there absolutely no error management or type checking. Process wise, I first came up with a grammar without the production
^^ ...that would parse your example, then added theExprtypes but without the eval method, then the production^^ ..., then I finally added the eval methods to theExprtrait and sub-classes.