码迷,mamicode.com
首页 > 编程语言 > 详细

State Monad in C++

时间:2015-03-11 21:31:23      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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

#include <functional>

template<template<typename> class M> struct Monad {
    template<typename A> M<A> ret(A) = 0;
    template<typename A, typename B> M<B> bind(M<A>, std::function<M<B>(A)>) = 0;
};

template <typename A, typename B> struct Tuple{
    A _1;
    B _2;
};

template<typename S> struct State {
    template <typename A> struct type : Monad<type> {
        std::function<Tuple<S, A>(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;
        }
    };
};

State Monad in C++

标签:

原文地址:http://www.cnblogs.com/ski-comb/p/4330924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!