Created
April 8, 2020 19:21
-
-
Save Bloodb0ne/55532bd616d3f2102b2b6a022542a7b6 to your computer and use it in GitHub Desktop.
Parser Combinators Math Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
constexpr auto single_sum = [](auto)->std::function<int(int, int)> { return [](int a, int b) { return a + b; }; }; | |
constexpr auto single_sub = [](auto)->std::function<int(int, int)> { return [](int a, int b) { return a - b; }; }; | |
constexpr auto single_mul = [](auto)->std::function<int(int, int)> { return [](int a, int b) { return a * b; }; }; | |
constexpr auto single_div = [](auto)->std::function<int(int, int)> { return [](int a, int b) { return a / b; }; }; | |
constexpr auto prefix_double = [](auto)->std::function<int(int)> { return [](int a) { return a * a; }; }; | |
constexpr auto prefix_neg = [](auto)->std::function<int(int)> { return [](int a) { return -a; }; }; | |
auto mathParser = | |
LeftBinOper('+'_symb % single_sum || '-'_symb % single_sub) >>= | |
LeftBinOper('*'_symb % single_mul || '/'_symb % single_div) >>= | |
Prefix('-'_symb % prefix_neg || '!'_symb % prefix_double) >>= | |
ParseNumber(); | |
std::string test_expression = "3*5*2+1*2+1+1+1+2+3+3"; | |
ctxStringIter start = test_expression.begin(); | |
ctxStringIter end = test_expression.end(); | |
decltype(mathParser)::return_type final_result; | |
bool hasParsed = mathParser(start, end, &final_result); | |
if (hasParsed) { | |
std::cout << "Parsed Successfully" << std::endl; | |
std::cout << "Result:= " << final_result << std::endl; | |
std::cout << "(line: " << start.getCurrentLine() << " col: " << start.getCurrentCol() << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment