void If::evaluate() {
	// empty list = false
	// not empty list = true
	// Im going to receive 3 arguments, if the first argument is
	// true then evaluate and return the second one
	// if the first argument is false (empty list) the evaluate and
	// return the third one
	std::vector<Expression*> myArguments = getArguments();
	std::vector<Expression*>::iterator it = myArguments.begin();
	Expression* condition = *it;
	++it;
	Expression* trueReturn = *it;
	++it;
	Expression* falseReturn = *it;

	// Start checking conditons
	condition->evaluate();
	if (condition->getResult() == LISP_FALSE){
		falseReturn->evaluate();
		result = falseReturn->getResult();
	} else {
		trueReturn->evaluate();
		result = trueReturn->getResult();
	}
}
int main()
{
	const int SIZE = 256;
	Expression* expression;
	char paren, comma, line[SIZE];

	ifstream fin("input.txt");

	while (true)
	{
		symbolTable.init();
		fin.getline(line, SIZE);
		if (!fin) break;

		stringstream in(line, ios_base::in);

		in >> paren;
		cout << line << " ";

		try
		{
			expression = SubExpression::parse(in);
			in >> comma;
			parseAssignments(in);
			cout << "Value = " << expression->evaluate() << endl;
		}
		catch (exception) {
			return EXIT_FAILURE;
		}
	}
	return 0;
}
int main(int argc, char** argv) {
    

    ifstream inFile;
    char inputFilename[] = "F:\\Documents\\project2input.txt";
    inFile.open(inputFilename, ios::in);

    if (!inFile) {
        cerr << "Can't open input file " << inputFilename << endl;
        exit(1);
    }
    Expression* expression;
    
    std::string token;
    std::istringstream line(token);
    char paren, comma;
    while(std::getline(inFile, token))
    {
        
        std::istringstream line(token);
        while(line >> token)
        {
            std::cout << "Token :" << token << std::endl;
            line >> paren;
            expression = SubExpression::parse();
            line >> comma;
            parseAssignments();
        }
    }
    
    
    cout << "Value = " << expression->evaluate() << endl;
    inFile.close();
    return 0;
}
Variable* Variable::getVariable(int depth, vector<Expression>& index, Function* origin)
{
	if(index.size() <= 0)
	{
		return this;
	}
	if(depth == index.size() || !origin)
	{
		return this;
	}
	else
	{	
		if(depth < index.size() && depth >= 0)
		{
			Expression a = index[depth];
			Variable v = a.evaluate(origin);
			int i = v.getValuef();
			if(i < variables.size() && i >= 0)
			{
				return variables[i].getVariable(depth+1, index, origin);	
			}
			else
			{
				return this;
			}
		}
		else
		{
			return this;
		}
	}		
	return this;
}
Element* Function::to_element(ContextProtected& context) {
	ExpressionParser parser;
	Expression* expression = parser(this->sentence);
	Environment* env = expression->evaluate(context);
	delete expression;
	Element* element = env->get_elements()[0]->clone();
	delete env;
	return element;
}
bool evaluatePredicate(const Expression& expression)
{
    Value result(expression.evaluate());

    // foo[3] means foo[position()=3]
    if (result.isNumber())
        return EqTestOp(EqTestOp::OP_EQ, Function::create(ASCIILiteral("position")), std::make_unique<Number>(result.toNumber())).evaluate().toBoolean();

    return result.toBoolean();
}
    virtual bool evaluate()
    {
        switch(_operator)
        {
        case LESS:
            return _left->value() < _right->value();
        case MORE:
            return _left->value() > _right->value();
        case EQUAL:
            return fabs(_left->value() - _right->value()) <= 0.000001;
        case AND:
            return _left->evaluate() && _right->evaluate();
        case OR:
            return _left->evaluate() || _right->evaluate();
        default:
            throw "Unknown operator";

        }
    }
Exemple #8
0
int main( int, char*[] )
{
    std::string code = "(test 42 ( - 44 ( + 1 1 ) ) )  ";
    Compiler compiler(code);

    Expression* program = compiler.compile();
    
    printValue( program->evaluate() );

    std::cout << std::endl << " ---DONE--- " << std::endl;
}
int main()
{
	Expression* expression;
	char paren, comma;
	cout << "Enter expression: ";
	cin >> paren;
	expression = SubExpression::parse();
	cin >> comma;
	parseAssignments();
	cout << "Value = " << expression->evaluate() << endl;
	return 0;
}
Exemple #10
0
  virtual bool evaluate(SimpleCpcClient* c, const SimpleCpcClient::Process & p){
    bool run = on_empty;
    for(size_t i = 0; i<m_cond.size(); i++){
      if(m_cond[i]->evaluate(c, p)){
	run = true;
	break;
      }
    }
    if(run)
      return m_rule->evaluate(c, p);
    return false;
  }
Number Application::calculate(const std::string &input, int precision) const
{
    // tokenizujemy
    Tokenizer tok(input);
    std::vector<Token*> tokens = tok.tokenize();

    Expression *expr = 0;

    try {
        // sprawdzamy sens
        SyntaxChecker checker(tokens);
        checker.check();

        // parser
        Parser parser(tokens, m_precedence);
        expr = parser.parse();
    } catch (...) {
        // usuwanie tokenów
        for (Token *tok : tokens) {
            delete tok;
        }

        throw;
    }

    // rekurencyjnie liczymy rozwiązanie
    Number out;

    try {
        out = expr->evaluate(0, precision);
    } catch (...) {
        // usuwanie wyrażeń
        delete expr;

        // usuwanie tokenów
        for (Token *tok : tokens) {
            delete tok;
        }

        throw;
    }

    // usuwanie wyrażeń
    delete expr;

    // usuwanie tokenów
    for (Token *tok : tokens) {
        delete tok;
    }

    return out;
}
Exemple #12
0
void processCell(Expression &expr, double x, double y, double xLen, double yLen, std::vector<sf::Vertex> &Curve) {
	double a, b, c, d;
	a = expr.evaluate(x, -y);
	b = expr.evaluate(x + xLen, -y);
	c = expr.evaluate(x + xLen, -y - yLen);
	d = expr.evaluate(x, -y - yLen);
	int num = ((a > 0.0) ? 1 : 0) + ((b > 0.0) ? 2 : 0) + ((c < 0.0) ? 4 : 0) + ((d > 0.0) ? 8 : 0);
	switch(num) {
		case 1: case 2: case 4: case 7: case 8: case 11: case 13: case 14: case 3: case 6: case 12: case 9:
			draw(num, x, y, xLen, yLen, a, b, c, d, Curve);
//			std::cout<<"["<<x<<","<<y<<","<<num<<"]\t";
			break;
		case 5: case 10:
			std::cout << "Recursion Happens\n";
			processCell(expr, x, y, xLen / 2, yLen / 2, Curve);
			processCell(expr, x + xLen / 2, y, xLen / 2, yLen / 2, Curve);
			processCell(expr, x + xLen / 2, y + yLen / 2, xLen / 2, yLen / 2, Curve);
			processCell(expr, x, y + xLen / 2, xLen / 2, yLen / 2, Curve);
			break;
		case 0: case 15:
			break;
	}
}
/* performs and outputs the choice expression in the output style */
void runSilent(std::string choice,std::string strExpr,std::string output) {
	Expression::Notation notation = Expression::NOTATION_INFIX;
	Expression* expression = NULL;
	bool isValidSelection = true;
	
	if(choice == "infix"){
		notation = Expression::NOTATION_INFIX;
	}
	else if(choice == "postfix"){
		notation = Expression::NOTATION_POSTFIX;
	}
	else if(choice == "prefix"){
		notation = Expression::NOTATION_PREFIX;
	}
	else{
		isValidSelection = false;
	}

	if(isValidSelection){
		expression = new Expression(strExpr,notation);

		if(!expression->hasError()){
			if(output == "infix")
			cout << expression->getInfix() << endl;
			else if(output == "postfix")
			cout << expression->getPostfix() << endl;
			else if(output == "prefix")
			cout << expression->getPrefix() << endl;
			else if(output == "value"){
				try{
					cout << expression->evaluate() << endl;
				}
				catch (runtime_error& e)
				{
					cout << e.what() << endl;
				}
			}
			else
				cout << "invalid output format." << endl;
		}
		else{
			cout << expression->getError() << endl;
		}
	}
	else{
		cout << "The selection you entered was not valid." << endl;
	}

	delete expression;
}
Exemple #14
0
int
for_each(Vector<SimpleCpcClient*>& list, Expression & expr){
  for(size_t i = 0; i<list.size(); i++){
    if(list[i] == 0)
      continue;
    Properties p;
    Vector<SimpleCpcClient::Process> procs;
    if(list[i]->list_processes(procs, p) != 0){
      ndbout << "Failed to list processes on " 
	     << list[i]->getHost() << ":" << list[i]->getPort() << endl;
    }
    for(size_t j = 0; j<procs.size(); j++)
      expr.evaluate(list[i], procs[j]);
  }
  return 0;
}
Exemple #15
0
int main()
{
    Tokenizer t;

    //adding the tokens for the tokenizer
    t.add("\\+|-",PLUSMINUS);
    t.add("\\*|/",MULTDIV);
    t.add("\\^",RAISED);
    t.add("!",FACULTY);
    //regexp matching is greedy; try sinh/cosh/tanh first
    t.add("sinh|cosh|tanh",FUNCTION);
    t.add("asin|acos|atan",FUNCTION);
    t.add("sin|cos|tan|sqrt",FUNCTION);
    t.add("log\\[[[[:digit:]]+(\\.)?[[:digit:]]*\\]|log",FUNCTION);
    t.add("\\(",OPEN_BRACKET);
    t.add("\\)",CLOSE_BRACKET);
    t.add("[[:digit:]]+(\\.)?[[:digit:]]*",NUMBER);

    string str;

    while(1) {
        cout << "=> ";

        if(!getline(cin,str)) {
          cout << endl;
          return 1;
        }

        str.erase(remove_if(str.begin(),str.end(), ::isspace),str.end());

        if(str.empty())
          continue;

        if(str == "quit")
            break;
        try{
            vector<token> a = t.tokenize(str);
            Parser p(a);
            Expression* exp = p.parse();
            cout << "\t\t== " << exp->evaluate() << endl;;
        } catch (runtime_error& e) {
            cout << "\t\tSyntax error: " << e.what() << endl;;
        }
    }

    return 0;
}
Exemple #16
0
int evaluate_file(char *filename) {
    ifstream file;
    Expression* expression;

    file.open(filename, ifstream::in);

    try {
        file >> &expression;
        expression->evaluate( Environment::globalEnvironment );
    }
    catch (SchemerException *e) {
       cerr << "Error in file " << filename << ": " << e << endl;
       cerr << "aborting." << endl;
       delete e;
    }

    return 0;
}
Exemple #17
0
int eval_print_loop() {
    stringstream stream (stringstream::in | stringstream::out);
    string line;
    Expression* expression;

    while (true) {

        stream.clear();

        cout << ">>> ";
        getline( cin, line );
        stream << line;

        stream.flush();

        /* if end of user input: exit */
        if (cin.eof()) {
            break;
        }

        try {
            expression = NULL;
            stream >> &expression;

            if (expression != NULL) {
                cout << "=> " << expression->evaluate( Environment::globalEnvironment ) << endl;
            }
        }
        catch (SchemerException *e) {
           cerr << "Error: " << e << endl;
           delete e;
        }

        gc_run( Environment::globalEnvironment );
    }
    cout << endl;

    return 0;
}
Exemple #18
0
int main() {
	Expression* expression;
	char paren, comma, line[maxLineSize];
	
	// Open file for reading.
	ifstream input(inputFileName);

	while(true) {
		input.getline(line, maxLineSize); // Fetch next line until we hit EOF
		if(!input) // If no more lines are found get out of the while loop.
			break;
		strstream in(line, maxLineSize);

		cout << line << " "; // Display the current line we are working with
		in >> paren; // Get rid of a parenthesis

		symbolTable.init(); // Clears all data in our symbol table.  

		try { // Run the evaluation algorthim and catch/report any errors we detect. 
			expression = SubExpression::parse(in);
			in >> comma;

			if(comma != ';') // No variables in this one.
				if(comma == ',')  // Check to make sure we have a comma if we 
					parseAssignments(in);
				else
					throw exception("Error: Syntax Error"); // There was no comma or semi-colon.

			double result = expression->evaluate();
			cout << "Value= " << result << endl;
		} catch(exception& mesg) {
			cout << mesg.what() << endl;
		}
	}
	// Keep window open until you press a key.
	cout << endl << "Execution complete: Press any key to exit";
	cin.get();
    return 0;
}
Exemple #19
0
double Expression::readToken(std::map<char, double>& substitutions, std::istream& in)
{
	char ch;
	eatwhite(in); // Skip whitespace

	in.get(ch);
	if ( isalpha(ch) )
		return substitutions[ch]; // Substitute a variable
	else if ( ch == '$' )
	{
		// Evaluate a subexpression
		Expression sub = local_subs.front();
		local_subs.pop_front();
		return sub.evaluate(substitutions);
	}
	else if ( isdigit(ch) || ch == '.' )
	{
		// Read a number
		in.putback(ch);
		double num;
		in >> num;
		return num;
	}
int main() {																// The main function
    string exp = "";														// initialize string
    while (exp != "#") {
        cout << "Please enter an expression: ";								// print
        getline(cin, exp);													// exp is the input entered
        if (exp.size() >= 3) {												// An expression must be >= to 3 in length
            exp = RemoveSpaces(exp);										// Remove spaces from the expression string
            bool correctInput = CheckInput(exp);							// If the input is correct
            if (correctInput) {												// The input correct
                // Add brackets to fix bedmas
                exp = Bedmas(exp, 0);										// Bedmas for division
                exp = Bedmas(exp, 1);										// Bedmas for multiplication
                exp = Bedmas(exp, 2);										// Bedmas for addition
                exp = Bedmas(exp, 3);										// Bedmas for subtraction
                Expression *ex;												// Initalize Expression object
                ArithmeticExpression *e = new ArithmeticExpression(exp);	// Create an object of ArithmeticExpression
                e->Split();													// call e’s split, call the recursive tree function
                if (!e->error) {											// If e’s member variable error is not true
                    ex = e;													// Set an Expression to an ArithmetricExpression to use fields not in Expression
                    ex->print();											// call ex’s print
                    printf(" = %.2f\n", atof(ex->evaluate().c_str()));		// print the rounded answer
                    delete e;												// Delete the ArithemeticExpression pointer
                }
            }
            else {
                cout << "Expression is not well formed" << endl;			// print expression
            }
        }
        else {
            if (exp != "#")													// if the expr is not #
                cout << "Expression is not well formed" << endl;			// error message
        }
        cout << endl;														// new line
    }
    return 0;																// return 0 to close program
}
Exemple #21
0
int main()
{
    map<string, double> externalVars;
    MyVariableStorage extVariableStorage(&externalVars);
    VariableStorage variableStorage;

    variableStorage.setExternalStorage(&extVariableStorage);
    cout << "libNumHop example executable!" << endl;

    externalVars.insert(pair<string,double>("dog", 55));
    externalVars.insert(pair<string,double>("cat", 66));
    std::vector<std::string> expr;
    expr.push_back("a=5;a=8;a;");
    expr.push_back("a=5;\n a=8\n a;");
    expr.push_back("a=1;b=2;c=3;d=a+b*c;d");
    expr.push_back("a=1;b=2;2^2;b^2;b^b;2^(1+1);b^(a+a)");
    expr.push_back("a=1;b=2;c=3;d=4;a=(3+b)+4^2*c^(2+d)-7*(d-1)");
    expr.push_back("a=1;b=2;c=3;d=4;a=(3+b)+4^2*c^(2+d)-7/6/5*(d-1)");
    expr.push_back("7/3/4/5");
    expr.push_back("7/(3/(4/5))");
    expr.push_back("(4/3*14*7/3/4/5*5/(4*3/2))");
    expr.push_back(" \t #   \n    a=5;\n #   a=8\n a+1; \r\n a+2 \r a+3 \r\n #Some comment ");
    expr.push_back("a=1; b=2; a-b; a-b+a");
    expr.push_back("a=1; b=2; -a+b; b-a; (-a)+b; b+(-a); ; b+(+a); b+a; +a+b");
    expr.push_back("a=1;b=2;c=3;d=4; a-b+c-d+a; a-b-c-d+a");
    expr.push_back("1-2*3-3*4-4*5;");
    expr.push_back("1-(-2-3-(-4-5))");
    expr.push_back("dog=4; 1-(-2-3-(-dog-5))");
    expr.push_back("-dog");
    expr.push_back("a=1;b=2;-(a-b)");
    expr.push_back("2e-2-1E-2; 1e+2+3E+2; 1e2+1E2");
    expr.push_back("value=5; value+2; value-2; value*1e+2");

    expr.push_back("cat \n dog \r dog=5;cat=2;a=3;b=dog*cat*a;b");
    expr.push_back("-1-2-3*4-4-3");
    expr.push_back("-1-(2-3)*4-4-3");
    expr.push_back("-(((-2-2)-3)*4)");

    expr.push_back("2--3; 1+-3; 1-+3; 1++3; 1---3");

    expr.push_back("2<3; 2<2; 4.2>2.5; (-4.2)>3; -4.2>3");
    expr.push_back("1|0; 0|0; 0|0|0|1; 1|1|1|1|1; 2|3|0; (-2)|3; (-1)|(-2) ");
    expr.push_back("1&0; 0&0; (-1)&1.5; 1&1; 1&1&1&0.4; 1&0&1");
    expr.push_back("2<3|4<2; 2<3&4<2; 2<3&4>2; x=2.5; (x>2&x<3)*1+(x>3&x<4)*2; x=3.6; (x>2&x<3)*1+(x>3&x<4)*2; ");

    expr.push_back("#The following will (should) not work!\n 2*-2; a += 5; 1+1-; = 5; 0.5huj");

    for (size_t i=0; i<expr.size(); ++i)
    {
        cout << endl;
        cout << expr[i] << endl;
        cout << "----------------------------------------------------------------" << endl;

        list<string> exprlist;
        extractExpressionRows(expr[i], '#', exprlist);

        for (list<string>::iterator it = exprlist.begin(); it!=exprlist.end(); ++it)
        {
            Expression e;
            bool interpretOK = interpretExpressionStringRecursive(*it, e);
            if (interpretOK)
            {
                bool evalOK;
                double value = e.evaluate(variableStorage, evalOK);
                double value2 = e.evaluate(variableStorage, evalOK); // evaluate again, should give same result
                cout << "Evaluating: ";
                if (evalOK)
                {
                    cout << "OK    : ";
                }
                else
                {
                    cout << "FAILED: ";
                }
                cout << e.print() << "\t\t Value: " << value << " " << value2 << endl;
            }
            else
            {
                cout << "Interpreting FAILED: " << *it << endl;
            }
        }
        cout << "----------------------------------------------------------------" << endl;
    }

    return 0;
}
// test function for expressions
int main() {
	
	ProductExpression *expression =
		new ProductExpression( 
			new PowerExpression( 
				new ConstantExpression( 5 ), 
				new ConstantExpression( 6 ) ),
			new NegateExpression(
				new SinExpression(
					new ConstantExpression( 19 ) ) ) );	
	
	InvertExpression *invExpression = new InvertExpression( expression );
	
	SumExpression *sumExpression = new SumExpression( 
		invExpression, new ConstantExpression( 2 ) );
			
	sumExpression->print();
	
	
	printf( "\n" );
	
	printf( "%f\n", sumExpression->evaluate() );
	
	printf( "Writing to file.\n" );
	
	char **pathSteps = new char*[2];
	pathSteps[0] = new char[10];
	pathSteps[1] = new char[10];
	
	sprintf( pathSteps[0], "test" );
	sprintf( pathSteps[1], "file" );
	
	int *stepLength = new int[2];
	stepLength[0] = 4;
	stepLength[1] = 4;
	
	Path *path = new Path( pathSteps, 2, stepLength, false );
	
	File *file = new File( path, "test.out", 8 );
	FileOutputStream *outStream = new FileOutputStream( file, false );
	
	char *error = outStream->getLastError();
	if( error != NULL ) {
		printf( "Error:  %s\n", error );
		delete error;
		}
	
	
	ExpressionSerializer::serializeExpression( sumExpression, outStream );
	
	delete outStream;
	delete file;
	
	printf( "Reading back in from file.\n" );
	
	pathSteps = new char*[2];
	pathSteps[0] = new char[10];
	pathSteps[1] = new char[10];
	
	sprintf( pathSteps[0], "test" );
	sprintf( pathSteps[1], "file" );
	
	stepLength = new int[2];
	stepLength[0] = 4;
	stepLength[1] = 4;
	
	path = new Path( pathSteps, 2, stepLength, false );
	
	
	file = new File( path, "test.out", 8 );
	FileInputStream *inStream = new FileInputStream( file );
	error = inStream->getLastError();
	if( error != NULL ) {
		printf( "Error:  %s\n", error );
		delete error;
		}
	
	
	Expression *readExpression;
	ExpressionSerializer::deserializeExpression( &readExpression, 
		inStream );
	
	delete inStream;
	delete file;
	
	readExpression->print();
	
	
	printf( "\n" );
	
	printf( "%f\n", readExpression->evaluate() );
	
	delete sumExpression;
	delete readExpression;
	
	return 0;
	} 
CAssemblerCommand* parseDirectiveConditional(Parser& parser, int flags)
{
    ConditionType type;
    std::wstring name;
    Expression exp;

    const Token& start = parser.peekToken();
    ConditionalResult condResult = ConditionalResult::Unknown;
    switch (flags)
    {
    case DIRECTIVE_COND_IF:
        type = ConditionType::IF;
        exp = parser.parseExpression();
        if (exp.isLoaded() == false)
        {
            parser.printError(start,L"Invalid condition");
            return new DummyCommand();
        }

        if (exp.isConstExpression())
        {
            ExpressionValue result = exp.evaluate();
            if (result.isInt())
                condResult = result.intValue != 0 ? ConditionalResult::True : ConditionalResult::False;
        }
        break;
    case DIRECTIVE_COND_IFDEF:
        type = ConditionType::IFDEF;
        if (parser.parseIdentifier(name) == false)
            return nullptr;
        break;
    case DIRECTIVE_COND_IFNDEF:
        type = ConditionType::IFNDEF;
        if (parser.parseIdentifier(name) == false)
            return nullptr;
        break;
    }

    parser.pushConditionalResult(condResult);
    CAssemblerCommand* ifBlock = parser.parseCommandSequence(L'.', {L".else", L".elseif", L".elseifdef", L".elseifndef", L".endif"});
    parser.popConditionalResult();

    // update the file info so that else commands get the right line number
    parser.updateFileInfo();

    CAssemblerCommand* elseBlock = nullptr;
    const Token &next = parser.nextToken();
    const std::wstring stringValue = next.getStringValue();

    if (stringValue == L".else")
    {
        ConditionalResult elseResult = condResult;
        switch (condResult)
        {
        case ConditionalResult::True:
            elseResult = ConditionalResult::False;
            break;
        case ConditionalResult::False:
            elseResult = ConditionalResult::True;
            break;
        }

        parser.pushConditionalResult(elseResult);
        elseBlock = parser.parseCommandSequence(L'.', {L".endif"});
        parser.popConditionalResult();

        parser.eatToken();	// eat .endif
    } else if (stringValue == L".elseif")
    {
        elseBlock = parseDirectiveConditional(parser,DIRECTIVE_COND_IF);
    } else if (stringValue == L".elseifdef")
    {
        elseBlock = parseDirectiveConditional(parser,DIRECTIVE_COND_IFDEF);
    } else if (stringValue == L".elseifndef")
    {
        elseBlock = parseDirectiveConditional(parser,DIRECTIVE_COND_IFNDEF);
    } else if (stringValue != L".endif")
    {
        return nullptr;
    }

    // for true or false blocks, there's no need to create a conditional command
    if (condResult == ConditionalResult::True)
    {
        delete elseBlock;
        return ifBlock;
    }

    if (condResult == ConditionalResult::False)
    {
        delete ifBlock;
        if (elseBlock != nullptr)
            return elseBlock;
        else
            return new DummyCommand();
    }

    CDirectiveConditional* cond;
    if (exp.isLoaded())
        cond = new CDirectiveConditional(type,exp);
    else if (name.size() != 0)
        cond = new CDirectiveConditional(type,name);
    else
        cond = new CDirectiveConditional(type);

    cond->setContent(ifBlock,elseBlock);
    return cond;
}
int main() {

	std::cout
			<< "Démonstration de ValueModel et des opérateurs Unaires / Binaires"
			<< std::endl;

	ValueModel<double> val(0.8);
	ValueModel<double>* val_ptr;
	cout << val.evaluate() << " et après modification : ";
	val_ptr = &val;
	val_ptr->setValue(0.7);
	cout << val_ptr->evaluate() << endl;

	ValueModel<double> val2(0.9);
	ValueModel<double>* val_ptr2 = 0;
	val_ptr2 = &val2;
	val_ptr2->setValue(0.5);
	//cout<<val_ptr2->evaluate()<< endl;

	fuzzy::NotMinus1<double> opNot;
	fuzzy::AndMin<double> opAnd;
	fuzzy::OrMax<double> opOr;
	fuzzy::ThenMin<double> opThen;
	fuzzy::AggMax<double> opAgg;
	fuzzy::CogDefuzz<double> opDefuzz(0, 25, 1);
	UnaryExpressionModel<double>* unary_ptr = 0;
	UnaryExpressionModel<double> uem(&opNot, val_ptr);

	unary_ptr = &uem;
	UnaryShadowExpression<double> usem(unary_ptr);
	cout << "Démonstration de l'UnaryShadowExpression avec l'opérateur Not : "
			<< usem.getTarget()->evaluate(unary_ptr) << endl;
	cout << unary_ptr->GetOperator()->evaluate(val_ptr) << endl;

	BinaryExpressionModel<double>* binary_ptr;
	BinaryExpressionModel<double> bem(&opAnd, val_ptr, val_ptr2);
	binary_ptr = &bem;
	BinaryShadowExpression<double> bsem(binary_ptr);
	cout
			<< "Démonstration de la BinaryShadowExpression avec l'opérateur AndMin : "
			<< binary_ptr->GetLeft()->evaluate() << "     "
			<< binary_ptr->GetRight()->evaluate() << endl;
	cout << bsem.getTarget()->evaluate(val_ptr, val_ptr2) << endl;

	binary_ptr->SetOperator(&opDefuzz);
	cout
			<< "Démonstration de la BinaryShadowExpression avec l'opérateur Défuzz: "
			<< binary_ptr->GetOperator()->evaluate(val_ptr, val_ptr2) << endl;

	//final test
	//operators
	/*
	 fuzzy::NotMinus1<double> opNot;
	 fuzzy::AndMin<double> opAnd;
	 fuzzy::OrMax<double> opOr;
	 fuzzy::ThenMin<double> opThen;
	 fuzzy::AggMax<double> opAgg;
	 fuzzy::CogDefuzz<double> opDefuzz(0, 25, 1);
	 */
	//fuzzy expression factory
	fuzzy::FuzzyFactory<double> f(&opNot, &opAnd, &opOr, &opThen, &opAgg,
			&opDefuzz);
	//membership function
	fuzzy::isTriangle<double> poor(-5, 0, 5);
	fuzzy::isTriangle<double> good(0, 5, 10);
	fuzzy::isTriangle<double> excellent(5, 10, 15);
	fuzzy::isTriangle<double> cheap(0, 5, 10);
	fuzzy::isTriangle<double> average(10, 15, 20);
	fuzzy::isTriangle<double> generous(20, 25, 30);
	//unary_ptr->SetOperator(&poor);
	//cout <<"test unary" << unary_ptr->GetOperator()->evaluate(val_ptr) << endl;

	//values
	ValueModel<double> service(0);
	ValueModel<double> food(0);
	ValueModel<double> tips(0);
	ValueModel<double>* val_ptrs;
	ValueModel<double>* val_ptrf;
	ValueModel<double>* val_ptrt;
	val_ptrs = &service;
	val_ptrf = &food;
	val_ptrt = &tips;
	//fuzzy::SugenoThen<double> sugeno;
	//fuzzy::SugenoConclusion<double> sugenoC;
//	fuzzy::SugenoDefuzz<double> sugenoD;
	//NaryExpressionModel<double>();
	//f.NewIs(&tips, &cheap);
	Expression<double> *r = f.newAgg(
			f.newAgg(
					f.newThen(f.newIs(val_ptrs, &poor),
							f.newIs(val_ptrt, &cheap)),
					f.newThen(f.newIs(val_ptrs, &good),
							f.newIs(val_ptrt, &average))),
			f.newThen(f.newIs(val_ptrs, &excellent),
					f.newIs(val_ptrt, &generous)));
	//defuzzification

	Expression<double>* system = f.newDefuzz(val_ptrt, r, 0, 25, 1);

	//apply input
	float s;
	std::cout<< endl<<endl<<"Démonstration de l'application ( calcul de pourboire) de l'exemple du cours" << std::endl;
	//while (true) {
	 cout << "service : ";
	 cin >> s;
	 val_ptrs->setValue(s);
	 cout << "tips -> " << system->evaluate() << endl;
	 //};

	std::cout << endl << endl << "Démonstration de Sugeno conclusion : "
			<< std::endl;
	// Test sur SugenoConclusion
	std::vector<double> _coeff(3);
	cout << "Coeff 1 :";
	cin >> _coeff[0];
	cout << "Coeff 2 :";
	cin >> _coeff[1];
	cout << "Coeff 3 :";
	cin >> _coeff[2];
	for (int i = 0; i < 3; i++) {
		std::cout << _coeff[i] << std::endl;
	}

	core::ValueModel<double> test1(1);
	core::ValueModel<double> test2(2);
	core::ValueModel<double> test3(5);
	fuzzy::SugenoConclusion<double> sugConc(&_coeff);
	std::vector<core::Expression<double>*> tabExp;
	tabExp.push_back(&test1);
	tabExp.push_back(&test2);
	tabExp.push_back(&test3);
	for (int i = 0; i < 3; i++) {
		std::cout << tabExp.at(i) << std::endl;
	}

	//sugConc.evaluate(&tabExp);
	std::cout << "Sugeno Conclusion : " << sugConc.evaluate(&tabExp)
			<< std::endl;

	//SugenoDefuzz et donc sur SugenoThen

	fuzzy::SugenoThen<double> sugThen;
	std::cout << "Sugeno Then : " << sugThen.evaluate(&test3, &test2)
			<< std::endl;
	std::cout << "Premise Value " << sugThen.getPremiseValue() << std::endl;

	// fuzzy::SugenoDefuzz<double> sugDef;
	// std::cout << "Sugeno Defuzz : " << sugDef.evaluate(&tabExp) << std::endl;

	//Test
	std::cout << endl << endl
			<< "Démonstration de l'application pour le calcul de la qualité d'un restaurant "
			<< std::endl;
	fuzzy::isTriangle<double> badQuality(-5, 0, 5);
	fuzzy::isTriangle<double> averageQuality(5, 10, 15);
	fuzzy::isTriangle<double> excellentQuality(15, 20, 25);

	Expression<double> *r1 = f.newAgg(
			f.newAgg(
					f.newThen(f.newIs(val_ptrs, &poor),
							f.newIs(val_ptrf, &badQuality)),
					f.newThen(f.newIs(val_ptrs, &good),
							f.newIs(val_ptrf, &averageQuality))),
			f.newThen(f.newIs(val_ptrs, &excellent),
					f.newIs(val_ptrf, &excellentQuality)));
	Expression<double>* system1 = f.newDefuzz(val_ptrf, r1, 0, 25, 1);
	float fo;
	float result, result2;
	float savFood, savServ;
	std::cout<<"L'univers de définition est de -4.99 à 5 pour les valeurs à saisir " << std::endl;
	while (true) {

		cout << "qualité du repas : "******"tips -> " << system1->evaluate() << endl;
		cout << "service : ";
		cin >> s;
		if (s == 5) {
			s = 4.999;
		}
		if (s == 0) {
			s = 0.00001;
		}
		val_ptrs->setValue(s);
		savServ = system->evaluate();
		//cout << "tips -> " << system->evaluate() << endl;

		result = savServ + savFood;

		result2 = savServ / 2 + savFood;

		if (fo >= s) {
			if (result >= 23) {
				std::cout << "C'est un très bon restaurant" << std::endl;
			} else {
				if (result >= 20) {
					std::cout << "C'est un bon restaurant" << std::endl;
				} else {
					if (result >= 16) {
						std::cout << "C'est un restaurant convenable"
								<< std::endl;
					} else {
						std::cout << "C'est un mauvais restaurant" << std::endl;
					}
				}
			}
		} else {
			if (result2 >= 16.5) {
				std::cout << "C'est un très bon restaurant" << std::endl;
			} else {
				if (result2 >= 14) {
					std::cout << "C'est un bon restaurant" << std::endl;
				} else {
					std::cout << "C'est un mauvais restaurant" << std::endl;
				}
			}

		}

	}

	return 0;
}
Exemple #25
0
QVariant Engine::evaluate(Expression ex)
{
	return ex.evaluate();
}
/*
Ask the user what type of expression
Let the user enter an expression
Display the conversions and value, or an error
*/
void runNormal(){
	string choice;
	string expressionStr;
	Expression *expression = NULL;
	Expression::Notation notation = Expression::NOTATION_INFIX;
	bool isValidSelection = true;

	cout << "Select the notation of your expression:" << endl;
	cout << "1) Infix   (Traditional)." << endl;
	cout << "2) Postfix (Reverse Polish)." << endl;
	cout << "3) Prefix  (Polish)." << endl;
	cout << endl;
	getline(cin,choice);
	cout <<endl;
	if(choice == "1" || choice == "infix" || choice == "Infix"){
		notation = Expression::NOTATION_INFIX;
	}
	else if(choice == "2" || choice == "postfix" || choice == "Postfix"){
		notation = Expression::NOTATION_POSTFIX;
	}
	else if(choice == "3" || choice == "prefix" || choice == "Prefix"){
		notation = Expression::NOTATION_PREFIX;
	}
	else{
		isValidSelection = false;
	}

	if(isValidSelection){
		if(notation == Expression::NOTATION_INFIX){
			cout << "Enter your expression in infix notation:" << endl;
		}
		else if(notation == Expression::NOTATION_POSTFIX){
			cout << "Enter your expression in postfix notation:" << endl;
		}
		else if(notation == Expression::NOTATION_PREFIX){
			cout << "Enter your expression in prefix notation:" << endl;
		}
		
		getline(cin,expressionStr);
		cout << endl;
		expression = new Expression(expressionStr,notation);

		if(!expression->hasError()){
			string outputType = "infix";

			if(notation == Expression::NOTATION_INFIX)
			{
				cout << 
					"Would you like to convert to prefix or postfix?" << endl;
				getline(cin,outputType);

				if(outputType != "postfix")
					outputType == "prefix";
				cout << endl;
			}

			if(outputType == "infix")
			cout << "Infix: " << expression->getInfix() << endl;
			else if(outputType == "postfix")
			cout << "Postfix: " << expression->getPostfix() << endl;
			else
			cout << "Prefix: " << expression->getPrefix() << endl;
			try{
				cout << "Result: " << expression->evaluate() << endl;
			}
			catch (runtime_error& e)
			{
				cout << e.what() << endl;
			}
		}
		else{
			cout << "There was a problem ";
			cout << "with the expression you entered:" << endl;
			cout << expression->getError() << endl;
		}
	}
	else{
		cout << "The selection you entered was not valid." << endl;
	}

	delete expression;
}
Exemple #27
0
/*
 * Esplora lo spazio di ricerca per provare tutte le sostituzioni
 * possibili di variabili. Quando ha trovato una sostituzione valida
 * prova a valutare la regola, se e` soddisfatta la potremo aggiungere
 * al conflict set
 */
list<RuleApplication>
RuleSet::solve_search_tree(vector<string> *variables, vector<DTArrayItem> *values, Rule *rule, Fact *fact) {
  /* L'algoritmo seguito qui consta di due passi principali:
   *   1. Creiamo una sorta di cache per i possibili valori che
   *      le variabili possono assumere (gia` fatto in explode_var_values)
   *   2. Esplodiamo l'albero con tutte le possibili combinazioni
   *      variabile/valore. In realta` qui non utilizziamo un albero
   *      vero e proprio ma un vettore di tanti elementi quante sono
   *      i valori che le variabili possono assumere, pero` l'esplorazione
   *      avviene come se fosse un albero
   */

  Expression *expr = rule->get_lhs();
  list<RuleApplication> ret;
  FuncMemory funcmem;
  uint32_t i;
  uint32_t attribute_no = values->size();
  uint32_t var_no = variables->size();
  int32_t pos;

  if (variables->size() == 0) {
    /* se non ci sono variabili valutiamo la regola direttamente */
    if (expr->evaluate(&funcmem, fact)) {
      debug(rule->get_name());
      RuleApplication r;
      r.rule = rule;
      r.funcmem = funcmem;

      ret.push_back(r);
    }

    return ret;
  }

  vector<Variable> resolved_vars;
  vector<uint32_t> idx(var_no);
  for (i = 0; i < var_no; i++) {
    Variable tmp;
    tmp.varname = (*variables)[i];
    tmp.value = (*values)[0];
    resolved_vars.push_back(tmp);
    idx[i] = 0;
  }

  bool resolved = false;
  while (!resolved) {
    funcmem.clear();

    /* costruisci una FuncMemory con i valori puntati dagli indici delle
     * variabili. Tale FuncMemory sara` poi quella che verra` usata durante
     * la verifica della regola.
     */
    pos = var_no;
    while (pos-- > 0)
      funcmem[resolved_vars[pos].varname] = resolved_vars[pos].value;

    if (expr->evaluate(&funcmem, fact)) {
      /* la regola e` risultata applicabile, aggiungiamola alla lista di
       * applicazioni possibili
       */
      debug(rule->get_name());
      RuleApplication r;
      r.rule = rule;
      r.funcmem = funcmem;

      ret.push_back(r);
    }

    /* controlla se abbiamo finito */
    for (i = 0; i < var_no; i++) {
      resolved = (idx[i] == attribute_no - 1);
      if (!resolved) break;
    }

    if (resolved) break;

    /* altrimenti incrementa il contatore degli indici */
    increment_idxs(&idx, var_no, attribute_no, &resolved_vars, values);
  }

  return ret;
};