State Monad in C++

一个C++版本的State Monad。 需要C++11。

#include <functional>



template<template<typename> class M> struct Monad {

    template<typename A> M<A> ret(A);

    template<typename A, typename B> M<B> bind(M<A>, std::function<M<B>(A)>);

};



template <typename A, typename B> struct Tuple{

    A _1;

    B _2;

};



template<typename S> struct State {

    template <typename C> struct type : Monad<type> {

        std::function<Tuple<S, C>(S)> runState;

        template<typename A> type<A> ret(A a){

            std::function<Tuple<S, A>(S)> f = [a](S s) -> Tuple<S, A> {

                Tuple < S, A > r;

                r._1 = s;

                r._2 = a;

                return r;

            };

            type<A> s;

            s.runState = f;

            return s;

        }

        template<typename A, typename B> type<B> bind(type<A> fa, std::function<type<B>(A)> f) {

            std::function<Tuple<S, B>(S)> fr = [fa, f](S s) -> Tuple<S, B> {

                std::function<Tuple<S, A>(S)> f0 = fa.runState;

                Tuple<A, B> r = f0(s);

                std::function<Tuple<S, A>(S)> f1 = f(r._2).runState;

                return f1(r._1);

            };

            type<B> s;

            s.runState = fr;

            return s;

        }

    };

};

你可能感兴趣的:(C++)