Expand description
The State monad transformer, adding stateful computations to any monad.
StateT
allows combining state operations with effects provided by the base monad.
For example, it can be combined with Option
to create stateful computations that
may fail, or with Result
to create stateful computations that may produce errors.
§Examples
use rustica::transformers::StateT;
use rustica::prelude::*;
// Create a StateT over Option that increments the state and returns it
let state_t: StateT<i32, Option<(i32, i32)>, i32> =
StateT::new(|s: i32| Some((s + 1, s)));
// Run with an initial state
let result = state_t.run_state(10);
assert_eq!(result, Some((11, 10)));
§State Manipulation and Composition
use rustica::transformers::StateT;
use rustica::prelude::*;
// Define a more complex state type
#[derive(Debug, Clone, PartialEq)]
struct Counter {
value: i32,
increments: i32,
}
// Create a state that increments the counter value
let increment: StateT<Counter, Option<(Counter, i32)>, i32> = StateT::new(|mut s: Counter| {
s.value += 1;
s.increments += 1;
Some((s.clone(), s.value))
});
// Create a StateT that doubles the counter value and returns the previous value
let double: StateT<Counter, Option<(Counter, i32)>, i32> = StateT::new(|mut s: Counter| {
let prev = s.value;
s.value *= 2;
s.increments += 1;
Some((s.clone(), prev))
});
// Compose state operations
let inc_and_double = increment.bind_with(
move |_| double.clone(),
|m, f| m.and_then(|(s, _)| f((s, 0)))
);
// Run with an initial state
let result = inc_and_double.run_state(Counter { value: 5, increments: 0 });
// After incrementing, value = 6, then we double to 12
// The final result is ((Counter{value: 12, increments: 2}, 6))
// where 6 is the value after increment (returned by double)
assert_eq!(result.map(|(s, v)| (s.value, s.increments, v)), Some((12, 2, 6)));
Structs§
- StateT
- A monad transformer that adds state capabilities to a base monad.
Type Aliases§
- State
Combiner - Type alias for a function that combines two state-value pairs into a new state-value pair
- State
Value Mapper - Type alias for a function that transforms a state-value pair to another state-value pair