Skip to content

Instantly share code, notes, and snippets.

@deque-blog
Last active January 29, 2017 14:30
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 deque-blog/0d48ded3f4ef7a7e47ba837f8cccaa74 to your computer and use it in GitHub Desktop.
Save deque-blog/0d48ded3f4ef7a7e47ba837f8cccaa74 to your computer and use it in GitHub Desktop.
using env = std::map<id, nb>;
auto eval_alg(env const& env)
{
return [&env] (expression_r<int> const& e)
{
if (auto* o = get_as_add(e))
return boost::accumulate(o->rands(), 0, std::plus<int>());
if (auto* o = get_as_mul(e))
return boost::accumulate(o->rands(), 1, std::multiplies<int>());
if (auto* v = get_as_var(e)) return env.find(*v)->second;
if (auto* i = get_as_cst(e)) return *i;
throw_missing_pattern_matching_clause();
};
}
int eval(env const& env, expression const& expr)
{
return cata<int>(eval_alg(env), expr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment