C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
exprtk_collatz.cpp
Go to the documentation of this file.
1/*
2 **************************************************************
3 * C++ Mathematical Expression Toolkit Library *
4 * *
5 * ExprTk Collatz Example *
6 * Author: Arash Partow (1999-2024) *
7 * URL: https://www.partow.net/programming/exprtk/index.html *
8 * *
9 * Copyright notice: *
10 * Free use of the Mathematical Expression Toolkit Library is *
11 * permitted under the guidelines and in accordance with the *
12 * most current version of the MIT License. *
13 * https://www.opensource.org/licenses/MIT *
14 * SPDX-License-Identifier: MIT *
15 * *
16 **************************************************************
17*/
18
19
20#include <cstdio>
21#include <string>
22
23#include "exprtk.hpp"
24
25
26template <typename T>
27void collatz()
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 exprtk::rtl::io::print<T> print("%3.0f ");
36
37 symbol_table_t symbol_table;
38 symbol_table.add_function("print",print);
39
40 compositor_t compositor(symbol_table);
41
42 // define function: collatz_trace(x)
43 compositor.add(
44 function_t("collatz_trace")
45 .var("x")
46 .expression
47 (
48 " while (x > 1) "
49 " { "
50 " x := (x % 2 == 0) ? x / 2 : 3x + 1; "
51 " print(x); "
52 " } "
53 ));
54
55 const std::string collatz_program =
56 " x := 0; "
57 " repeat "
58 " print(x += 1); "
59 " collatz_trace(x); "
60 " print('\n\n'); "
61 " until (x > 100); "
62 " println; ";
63
64 expression_t expression;
65 expression.register_symbol_table(symbol_table);
66
67 parser_t parser;
68 parser.enable_unknown_symbol_resolver();
69 parser.compile(collatz_program,expression);
70
71 expression.value();
72}
73
74int main()
75{
76 collatz<double>();
77 return 0;
78}
void collatz()
int main()