monadic/
state.rs

1//! A State monad implementation
2
3pub struct State<'a, S, A> { 
4  pub run_state: Box<dyn 'a + Fn(S) -> (A, S)>, 
5}
6
7impl<'a, S: 'a + Clone, A: 'a + Clone> State<'a, S, A> {
8
9  pub fn pure(x: A) -> Self {
10    State { run_state: Box::new( move |s: S| (x.clone(), s))}  // (s -> (a,s))
11  }
12
13  pub fn bind<B, F: 'a>(self, f: F) -> State<'a, S, B> 
14    where
15      F: Fn(A) -> State<'a, S, B>
16  {
17    State { run_state: Box::new( move |s: S| {
18                  let (v, s1) = (*self.run_state) (s); // let (v,s') = runState self s
19                  let g = f( v).run_state ;
20                  (* g) (s1)             // runState (f v) s'
21               })
22          }     
23  }
24
25  pub fn initial_state(self, s: S) -> (A, S) {
26       (*self.run_state) (s)
27  }
28  
29}
30
31pub fn get<'a, S: Clone>() -> State<'a, S, S> {
32   State { run_state: Box::new( |s: S| (s.clone(), s))} 
33}
34
35pub fn put<'a, S: Clone + 'a>( s: S) -> State<'a, S, ()> {
36   State { run_state: Box::new( move |_| ( (), s.clone()) )} 
37}
38
39/// macro for a `State<'a, S, A>` monad with a boxed `(s -> (a, s))` function
40#[macro_export]
41macro_rules! stdo {
42  (pure $e:expr                           ) => [State::pure($e)];
43  (let $v:ident = $e:expr ; $($rest:tt)*) => [State::pure($e).bind( move |$v| { stdo!($($rest)*)} )];
44  (_ <- $monad:expr ; $($rest:tt)* ) => [State::bind(($monad), move |_| { stdo!($($rest)*)} )];
45  ($v:ident <- pure $e:expr ; $($rest:tt)* ) => [State::bind( State::pure($e), move |$v| { stdo!($($rest)*)} )];
46  ($v:ident <- $monad:expr ; $($rest:tt)* ) => [State::bind(($monad), move |$v| { stdo!($($rest)*)} )];
47  ($monad:expr                            ) => [$monad];
48}
49
50