Skip to content

Instantly share code, notes, and snippets.

(defprotocol AIStrategy
(eval-turn
[this turn]
"Heuristic to score the value of a turn")
(maximizing?
[this turn]
"Whether the turn should minimize or maximize the transitions"))
(defn minimax
"Implements the minimax recursion:
* Call the leaf node evaluation if the depth is zero
* Otherwise goes one level deeper"
[ai turn depth]
(if (or (zero? depth) (turn/game-over? turn))
(eval-turn ai turn)
(minimax-step ai turn
(fn [_ transition]
(minimax ai
(defn minimax-step-by
"One stage of the minimax algorithm, with custom comparison functions"
[key-fn ai turn open-recur]
(minimax-step
ai turn open-recur
:min-fn (partial min-key key-fn)
:max-fn (partial max-key key-fn)))
(defn- human-player-winning?
[{:keys [blue red green] :as scores}]
(let [human-score (* 1.1 blue)]
(and (< red human-score) (< green human-score))))
(defn- limited-move-options?
[turn]
(< (count (turn/transitions turn)) 5))
(defn- in-late-game?
expression e = add({
cst(1),
cst(2),
mul({cst(0), var("x"), var("y")}),
mul({cst(1), var("y"), add({cst(2), var("x")})}),
add({cst(0), var("x")})
});
std::cout << para<std::string>(print_infix, e) << std::endl;
std::string print_infix_op_bad(op<add_tag, std::string> const& e)
{
return boost::algorithm::join(e.rands(), " + ");
}
std::string with_parens(std::string const& s)
{
return std::string("(") + s + ")";
}
template<typename Out, typename Algebra>
Out para(Algebra f, expression const& ast)
{
return f(
fmap(
[f](expression const& e) -> std::pair<Out, expression const*> {
return { para<Out>(f, e), &e };
},
ast.get()));
}
std::string print_op_infix(op<add_tag, std::pair<std::string, expression const*>> const& e)
{
auto fst = [](auto const& e) { return e.first; };
return boost::algorithm::join(e.rands() | transformed(fst), " + ");
}
std::string print_op_infix(op<mul_tag, std::pair<std::string, expression const*>> const& e)
{
auto wrap_addition = [](auto const& sub_expr) {
if (get_as_add(sub_expr.second->get()))
// CATAMORPHISM
Out catamorphism_algebra(
expression_r<Out> const& e);
// PARAMORPHISM
Out paramorphism_algebra(
expression_r<std::pair<Out, expression const*>> const& e);
expression e = add({
cst(1),
cst(2),
mul({cst(0), var("x"), var("y")}),
mul({cst(1), var("y"), add({cst(2), var("x")})}),
add({cst(0), var("x")})
});
std::cout << cata<std::string>(print_infix_bad, e) << std::endl;