prop_check_rs/
state.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use std::fmt::{Debug, Formatter};
use std::rc::Rc;

/// The `State` monad represents a stateful computation.<br/>
/// `State`モナドは状態付き計算を表します。
pub struct State<S, A> {
  pub(crate) run_f: Rc<dyn Fn(S) -> (A, S)>,
}

impl<S, A> Debug for State<S, A> {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    write!(f, "Fn")
  }
}

impl<S, A> Clone for State<S, A>
where
  S: 'static,
  A: Clone + 'static,
{
  fn clone(&self) -> Self {
    Self {
      run_f: self.run_f.clone(),
    }
  }
}

impl<S, A> State<S, A>
where
  S: 'static,
  A: Clone + 'static,
{
  /// Create a new State with a value.<br/>
  /// 値を返すStateを作成します。
  pub fn value(a: A) -> State<S, A> {
    Self::new(move |s| (a.clone(), s))
  }

  /// Create a new State.<br/>
  /// 新しいStateを作成します。
  pub fn new<T, B, F>(f: F) -> State<T, B>
  where
    F: Fn(T) -> (B, T) + 'static, {
    State { run_f: Rc::new(f) }
  }

  /// Alias for Self::value.<br/>
  /// Self::valueのエイリアス。
  pub fn pure<B>(b: B) -> State<S, B>
  where
    B: Clone + 'static, {
    Self::new(move |s| (b.clone(), s))
  }

  /// Run the State.<br/>
  /// Stateを実行します。
  pub fn run(self, s: S) -> (A, S) {
    (self.run_f)(s)
  }

  /// Map the State.<br/>
  /// Stateをマップします。
  pub fn map<B, F>(self, f: F) -> State<S, B>
  where
    F: Fn(A) -> B + 'static,
    B: Clone + 'static, {
    self.flat_map(move |a| Self::pure(f(a)))
  }

  /// FlatMap the State.<br/>
  /// Stateをフラットマップします。
  pub fn flat_map<B, F>(self, f: F) -> State<S, B>
  where
    F: Fn(A) -> State<S, B> + 'static,
    B: Clone + 'static, {
    State::<S, B>::new(move |s| {
      let (a, s1) = self.clone().run(s);
      f(a).run(s1)
    })
  }

  /// Compose two States.<br/>
  /// 2つのStateを合成します。
  pub fn and_then<B>(self, sb: State<S, B>) -> State<S, (A, B)>
  where
    A: Clone,
    B: Clone + 'static, {
    self.flat_map(move |a| sb.clone().flat_map(move |b| Self::pure((a.clone(), b))))
  }

  /// Get the state.<br/>
  /// 状態を取得します。
  pub fn get<T>() -> State<T, T>
  where
    T: Clone, {
    Self::new(move |t: T| (t.clone(), t))
  }

  /// Set the state.<br/>
  /// 状態を設定します。
  pub fn set<T>(t: T) -> State<T, ()>
  where
    T: Clone + 'static, {
    Self::new(move |_| ((), t.clone()))
  }

  /// Modify the state after get it.<br/>
  /// 状態を取得した後に変更します。
  pub fn modify<T, F>(f: F) -> State<T, ()>
  where
    F: Fn(T) -> T + 'static,
    T: Clone + 'static, {
    let s = Self::get();
    s.flat_map(move |t: T| Self::set(f(t)))
  }

  /// Execute the State and return a State with the result in the collection.<br/>
  /// Stateを実行し結果をコレクションに持つStateを返します。
  pub fn sequence(sas: Vec<State<S, A>>) -> State<S, Vec<A>> {
    Self::new(move |s| {
      let mut s_ = s;
      let actions = sas.clone();
      let mut acc: Vec<A> = vec![];
      for x in actions.into_iter() {
        let (a, s2) = x.run(s_);
        s_ = s2;
        acc.push(a);
      }
      (acc, s_)
    })
  }
}

impl<S, A> Default for State<S, A>
where
  S: Default + 'static,
  A: Default + Clone + 'static,
{
  fn default() -> Self {
    Self::new(|_| (A::default(), S::default()))
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use std::env;

  fn init() {
    env::set_var("RUST_LOG", "info");
    let _ = env_logger::builder().is_test(true).try_init();
  }

  pub mod laws {
    use super::*;

    #[test]
    fn test_left_identity_law() {
      init();
      let n = 10;
      let s = 11;
      let f = |x| State::<i32, i32>::pure(x);
      let result = State::<i32, i32>::pure(n).flat_map(f).run(s.clone()) == f(n).run(s);
      assert!(result);
    }

    #[test]
    fn test_right_identity_law() {
      init();
      let x = 10;
      let s = 11;
      let result = State::<i32, i32>::pure(x)
        .flat_map(|y| State::<i32, i32>::pure(y))
        .run(s.clone())
        == State::<i32, i32>::pure(x).run(s);
      assert!(result);
    }

    #[test]
    fn test_associativity_law() {
      init();
      let x = 10;
      let s = 11;
      let f = |x| State::<i32, i32>::pure(x * 2);
      let g = |x| State::<i32, i32>::pure(x + 1);
      let result = State::<i32, i32>::pure(x).flat_map(f).flat_map(g).run(s.clone()) == f(x).flat_map(g).run(s);
      assert!(result);
    }
  }

  #[test]
  fn pure() {
    init();
    let s = State::<u32, u32>::pure(10);
    let r = s.run(10);
    assert_eq!(r, (10, 10));
  }

  #[test]
  // #[should_panic]
  fn should_panic_when_running_with_null_state() {
    let state: State<Option<i32>, i32> = State::<Option<i32>, i32>::new(|s| (10, s));
    let result = state.run(None);
    assert_eq!(result, (10, None));
  }
}