Skip to content

Instantly share code, notes, and snippets.

@charlie-x
Created August 22, 2020 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlie-x/36fc55d80ad1f00c06cfb7e068a83aff to your computer and use it in GitHub Desktop.
Save charlie-x/36fc55d80ad1f00c06cfb7e068a83aff to your computer and use it in GitHub Desktop.
#include <iostream>
using std::cout, std::endl;
#include <string>
using std::string, std::to_string;
struct eat { constexpr eat(auto...){} };
constexpr auto Tree(auto left, long val, auto right) {
return [=](auto f) { return f(left, val, right); };
}
constexpr auto Leaf(long val) { return Tree(eat{}, val, eat{}); }
auto TreeVal = [](eat, long val, eat) { return val; };
auto TreeLeft = [](auto left, long, eat) { return left; };
auto TreeRight = [](eat, long, auto right) { return right; };
string traversal(auto tree) {
string out;
if constexpr (! std::is_same_v<decltype(tree(TreeLeft)),eat>)
(out += traversal(tree(TreeLeft))) += " ";
out += to_string(tree(TreeVal));
if constexpr (! std::is_same_v<decltype(tree(TreeRight)),eat>)
(out += " ") += traversal(tree(TreeRight));
return out;
}
int main()
{
auto l1 = Leaf(5);
auto l2 = Leaf(6);
auto t1 = Tree(l1, 3, l2);
auto l3 = Leaf(7);
auto l4 = Leaf(9);
auto t2 = Tree(l3, 4, l4);
auto t3 = Tree(t1, 8, t2);
cout << traversal(t3) << endl; // prints 5 3 6 8 7 4 9 !!!
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment