radn-rs/src/func/controlflow.rs
2023-05-26 10:03:53 +00:00

81 lines
2.0 KiB
Rust

use std::marker::PhantomData;
use super::*;
pub struct ControlFlowInstance<C>(ControlFlow<(), C>);
impl<C> WeakFunctor for ControlFlowInstance<C> {
type F<'a, A: 'a> = ControlFlow<A, C>
where
Self: 'a;
}
impl<'a, C: 'a> Functor<'a> for ControlFlowInstance<C> {
fn fmap<A: 'a, B: 'a>(f: impl 'a + FnOnce(A) -> B, fa: Self::F<'a, A>) -> Self::F<'a, B> {
match fa {
ControlFlow::Continue(c) => ControlFlow::Continue(c),
ControlFlow::Break(a) => ControlFlow::Break(f(a)),
}
}
}
impl<'a, C: 'a> Pure<'a> for ControlFlowInstance<C> {
fn pure<A: 'a>(a: A) -> Self::F<'a, A> {
ControlFlow::Break(a)
}
}
pub struct BindableMut<T: ?Sized, A, B, F>(A, F, PhantomData<B>, PhantomData<T>);
impl<
'a,
T: ?Sized + Functor<'a>,
A: 'a,
B: 'a,
F: 'a + FnMut(A) -> T::F<'a, ControlFlow<B, A>>,
> BindableMut<T, A, B, F>
{
pub fn new(a: A, f: F) -> Self {
BindableMut(a, f, PhantomData, PhantomData)
}
}
impl<
'a,
T: ?Sized + Functor<'a>,
A: 'a,
B: 'a,
F: 'a + FnMut(A) -> T::F<'a, ControlFlow<B, A>>,
> Iterative<'a> for BindableMut<T, A, B, F>
{
type B = B;
type T = T;
fn next(mut self) -> IterativeWrapped<'a, Self> {
let fstate = self.1(self.0);
T::fmap(
move |state| match state {
ControlFlow::Continue(next_a) => {
ControlFlow::Continue(BindableMut::new(next_a, self.1))
}
ControlFlow::Break(b) => ControlFlow::Break(b),
},
fstate,
)
}
}
/// Next [Iterative] state, wrapped.
pub type IterativeWrapped<'a, F> =
Wrap<'a, ControlFlow<<F as Iterative<'a>>::B, F>, <F as Iterative<'a>>::T>;
/// Value passed to [`Monad::iterate`].
pub trait Iterative<'a>: 'a + Sized {
/// [`ControlFlow::Break`].
type B: 'a;
/// Corresponding [`WeakFunctor`].
type T: 'a + ?Sized + WeakFunctor;
/// Get next state.
fn next(self) -> IterativeWrapped<'a, Self>;
}