numbers flex & bison - c++

I'm writing my first flex and bison program which is a simple calculator, and I'd like the calculator to support complex number operations.
But, I cannot manage to insert or even handle any complex numbers in it, since I need the flex to somehow handle both real value and image value of the complex number in the same time and pass it to the bison, and also I dont know how the bison could handle 2 parameters.
This is my flex file:
As you can see, I tried something but this doesnt even compile (with all the complex number procedure). And just for the record, a complex number would look like 1.000+2.111i, 3i, etc.

If you are going to want to perform arithmetic computations on your imaginary numbers you probably want to create a struct say, "img_t" which has two fields, say, real and img and then write functions that have signatures like "img_t img_add(img_t a, img_t b)". Then your bison productions will call these functions for each operator. Your yyunion should have a field img_t img. You could also do these functions inlne in the bison if you wanted. The key point is that you need a struct in your yyunion that holds an imaginary number.
typedef struct {
double real, img;
} img_t;
%yyunion {
:
:
img_t img;
};
:
:
expr_complex: expr_complex '+' expr_complex { $$ = img_add($1, $3); }
:
:
If you see an integer or double alone in the lex, do you want to turn that into an imaginary number? If that's the case, then you can do away with expr_int and expr_double and have all your lex tokens return img_t.
If you post some of the expressions you want to parse and evaluate I can make further comments.

Related

How to make input part of my code?

So I have this maths project where I have to write a program which calculates definite integral of a given function within the given boundaries. I've done this using C++ and CodeBlocks, but now I would like to try and make it possible to input function using cmd when I run my code in CodeBlocks, just like I input boundaries, so I don't have to edit this line of code every time I want to run it for different function. I realised that this would require actually using then this input ( e.g. "sqrt(pow(x,2)-1)" ) as part of the code when entered, and I really don't know how to do this or if it is possible at all, so any help is welcome.
This the part of the code which handles function:
double Formula(double x)
{
double a;
a = sqrt(x);
return a;
}
If you want to evaluate expression like "sqrt(pow(x,2)-1)", you have to:
parse the string and generate an AST (Abstract syntax tree) which describes the operations to execute
use an evaluation function on the AST
For example, if you have "sqrt(pow(x,2)-1)" in input, the AST could be represented like this:
function - sqrt
function - substract
function - pow
variable - x
integer - 2
integer - -1
You have to define the structures which will be used to represent your AST.
Then, to parse the query string you have 2 choices:
parse it yourself, count the parentheses etc...
use a tool to generate the parser: yacc + lex or under linux bison + flex. These tools require time to be used to them.
If you have just a little project to do, you may have to try to parse the input yourself to generate the AST.
If the project is a compilation project, you should use bison + flex, they are exactly made for that (but require time to be used to ! ).
Alternatively, integrate with a scripting language, make it do the function parsing and evaluation. It will be considerably slower though.
JavaScript interpreters are all over the place. Python is fairly popular, too. Some people like Lua.

Recognize a specific string from a string array without iteration

I'm writing a derivative calculator in C++, and in order to properly perform the derivation operations, I need to parse the input equation at various character indexes along the equation's string.
I'm using isdigit() to parse out the numerical values from the equation and then store them into a separate string array, however now I need to parse out the mathematical symbols from the equation to identify which operation I need to perform.
Is there any way I can modify (overwrite?) isdigit() to recognize custom values from a string array? I'd like to avoid iteration to make my code a little less cluttered, since I'm already going to be using plenty of loops for the rest of this program and I want my code to be easy to follow. Does overwriting and inheritance in C++ work similarly to inheritance in Java (with the exception of multiple inheritance/interfaces)?
Please refrain from posting solutions that are irrelevant to the scope of this question, IE; different approaches to deriving equations in C++, as I've used this approach for some fairly specific reasons.
Thanks
You can use the new powerful C++11 regular expressions library that does almost what ever parsing you want. This way, you'll avoid iterations and code cluttering.
You can just use strchr. (Not everyone will like the macros here, but they do make combining character classes easy.)
#define OPERATOR "+-*/"
#define DIGIT "0123456789"
// Is c an operator
if (strchr(OPERATOR, c)) {
// Yes it is
}
or:
// Is c an operator or a digit?
if (strchr(OPERATOR DIGIT, c)) {
// Yup
}
Overriding and Inheritance works more or less the same as in Java.
You need to define a function as virtual and redefine it in derived class.
I know the "Please refrain from posting...", but I've written a library that does function parsing and derivation.
It is available at https://github.com/B3rn475/MathParseKit
I hope you can find some tips there.

What is the most efficient way to recalculate attributes of a Boost Spirit parse with a different symbol table?

I'm using Boost Spirit to implement functionality in some software that allows the user to enter a mathematical equation that will be repeatedly applied to an input stream. Input stream values are represented as symbols using boost::spirit::qi::symbols which the user can reference in their equation. (e.g. out1 = 3 * in1 + in2)
Parsing and compiling the user's equation is not performance sensitive but calculating its output value is as it forms part of a time-critical pipeline.
The standard way Spirit is used within the documentation is to calculate the output (attribute) of an input as it is parsed. However, as between each calculation only the attribute values of the symbols (out1, in1, etc.) will have changed, it feels like there might be a more efficient way to achieve this, perhaps by caching the abstract syntax tree of the expression and reiterating through it.
What is the most efficient way to recalculate the value of this (fixed) equation given a new set of symbol values?
The standard way Spirit is used is not as limited as you seem to think.
While you can use it to calulate an immediate value on the fly, it is much more usual to build an AST tree in the output attribute, that can be transformed (simplified, optimized) and interpreted (e.g. emitting virtual machine or even assembly instructions).
The compiler tutorials show this in full fledged, but the calculator samples are very close to what you seem to be looking for: http://www.boost.org/doc/libs/1_55_0/libs/spirit/example/qi/compiler_tutorial/
calc1 in example/qi/compiler_tutorial/calc1.cpp
Plain calculator example demonstrating the grammar. The parser is a syntax
checker only and does not do any semantic evaluation.
calc2 in example/qi/compiler_tutorial/calc2.cpp
A Calculator example demonstrating the grammar and semantic actions using
plain functions. The parser prints code suitable for a stack based virtual
machine.
calc3 in example/qi/compiler_tutorial/calc3.cpp
A calculator example demonstrating the grammar and semantic actions using
phoenix to do the actual expression evaluation. The parser is essentially
an "interpreter" that evaluates expressions on the fly.
Here's where it gets interesting for you, since it stops doing the calculations during parsing:
calc4 in example/qi/compiler_tutorial/calc4.cpp
A Calculator example demonstrating generation of AST. The AST, once
created, is traversed,
To print its contents and
To evaluate the result.
calc5 in example/qi/compiler_tutorial/calc5.cpp
Same as Calc4, this time, we'll incorporate debugging support, plus error
handling and reporting.
calc6 in example/qi/compiler_tutorial/calc6.cpp
Yet another calculator example! This time, we will compile to a simple
virtual machine. This is actually one of the very first Spirit example
circa 2000. Now, it's ported to Spirit2.
calc7 in example/qi/compiler_tutorial/calc7/main.cpp
Now we'll introduce variables and assignment. This time, we'll also be
renaming some of the rules -- a strategy for a grander scheme to come ;-)
This version also shows off grammar modularization. Here you will see how
expressions and statements are built as modular grammars.
calc8 in example/qi/compiler_tutorial/calc8/main.cpp
Now we'll introduce boolean expressions and control structures. Is it
obvious now what we are up to? ;-)
I'm sure you'll find lots of inspiration towards the end of the tutorial!
You can build your own tree of calculator objects which mirrors the AST. So for your example out1 = 3 * in1 + in2 the AST is:
*
3
+
in1
in2
So you'd build an object hierarchy like this:
Multiplier(
Constant(3),
Adder(
Variable(&in1),
Variable(&in2)
)
)
With classes something like:
class Result {
virtual double value() = 0;
};
class Multiplier : public Result {
Multiplier(Result* lhs, Result* rhs);
double value() { return _lhs->value() * _rhs->value(); }
}

Interpret User-specified Mathematics

I have a program which loops through a number of data points, performs an operation on each data point, and returns a result for each data point. Say,
for(int i=1;i<LEN-1;++i)
result[i]=operate(userfunc,i);
Internally, I can define several variables which contain the values of various neighbours of the data point.
double operate(string userfunc, int i){
double next=data[i+1];
double prev=data[i-1];
double me=data[i];
userfunc(me,prev,next);
}
I imagine the user providing an input string containing the mathematical operation they'd like to perform along with the variables they'd like to work with, such as:
0.5+me*min(prev,next)
My question then is whether there exists a library which would facilitate parsing the user's input. My current thoughts include using Boost.Spirit or a number of regular expressions. But perhaps there is an easier way.

Return Set for a Command Parser

I need to write a parser to parse commands. 5 such commands are:
"a=10"
"b=foo"
"c=10,10"
"clear d"
"c push_back 2"
In the case of the first example, set is the command, a is the object and 10 is the value.
What do you think the parser should return for each line above?
Here is my idea:
"a=10" -> SET (COMMAND_ENUM), INT (VALUE_TYPE), "a", ("10")
"b=foo" -> SET (COMMAND_ENUM), STRING (VALUE_TYPE), "b", ("foo")
Is this a good approach? What is the standard approach for this problem? Should I dispatch instead?
I have a function which checks the type associated with an object. For example, a above is of type INT and must be assigned an INT value, otherwise the parser should return or throw an error of some sort. I also have a convert function for converting values from strings to the desired type. These throw if the conversion is not possible. If the parser tries to convert the values from strings to the required type, then it is probably a good idea to return them via a boost::variant.
You need to come up with at least a semi-formal grammar for the command language you want to recognize, since you've left a whole lot of things really vaguely specified (e.g. in b=foo you want b to be a variable name but foo to be a string literal. How do you distinguish them?. Does a sequence of characters represent an identifier if it's on the right side of an assignment, but a literal if it's on the left side? Or does a single character represent an identifier, but multiple characters represent a literal?) In c=10,10 does 10,10 represent a list or a vector? Writing a grammar will at least force you to think about such things, and it will also serve at least as a guide to how to write your parser (at most it will be something that can be automatically translated into your parser).
You're on the right track by thinking of how statements should be represented as Abstract Syntax Trees (ASTs), but you need to take a step backwards and look at what you want in terms of concrete syntax.