A C + + version of State Monad. Need c++11.
#include <functional>Template<template<typename>classM>structMonad {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>structtuple{A _1; B _2;}; Template<typename s>structState {Template<typename a>structType: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; returnR; }; Type<A>s; S.runstate=F; returns; } 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; returnF1 (r._1); }; Type<B>s; S.runstate=fr; returns; } };};
State Monad in C + +