| 25 | |
| 26 | template <typename T> |
| 27 | void fibonacci() |
| 28 | { |
| 29 | typedef exprtk::symbol_table<T> symbol_table_t; |
| 30 | typedef exprtk::expression<T> expression_t; |
| 31 | typedef exprtk::parser<T> parser_t; |
| 32 | typedef exprtk::function_compositor<T> compositor_t; |
| 33 | typedef typename compositor_t::function function_t; |
| 34 | |
| 35 | T x = T(0); |
| 36 | |
| 37 | compositor_t compositor; |
| 38 | |
| 39 | compositor.add( |
| 40 | function_t("fibonacci") |
| 41 | .var("x") |
| 42 | .expression |
| 43 | ( |
| 44 | " switch " |
| 45 | " { " |
| 46 | " case x == 0 : 0; " |
| 47 | " case x == 1 : 1; " |
| 48 | " default : " |
| 49 | " { " |
| 50 | " var prev := 0; " |
| 51 | " var curr := 1; " |
| 52 | " while ((x -= 1) > 0) " |
| 53 | " { " |
| 54 | " var temp := prev; " |
| 55 | " prev := curr; " |
| 56 | " curr += temp; " |
| 57 | " }; " |
| 58 | " }; " |
| 59 | " } " |
| 60 | )); |
| 61 | |
| 62 | symbol_table_t& symbol_table = compositor.symbol_table(); |
| 63 | symbol_table.add_constants(); |
| 64 | symbol_table.add_variable("x",x); |
| 65 | |
| 66 | std::string expression_str = "fibonacci(x)"; |
| 67 | |
| 68 | expression_t expression; |
| 69 | expression.register_symbol_table(symbol_table); |
| 70 | |
| 71 | parser_t parser; |
| 72 | parser.compile(expression_str,expression); |
| 73 | |
| 74 | for (std::size_t i = 0; i < 40; ++i) |
| 75 | { |
| 76 | x = static_cast<T>(i); |
| 77 | |
| 78 | const T result = expression.value(); |
| 79 | |
| 80 | printf("fibonacci(%3d) = %10.0f\n", |
| 81 | static_cast<int>(i), |
| 82 | result); |
| 83 | } |
| 84 | } |