radn-rs/src/func/instances/lazy.rs
2023-05-26 11:14:59 +00:00

117 lines
3.2 KiB
Rust

//! Helper [Monad]s to defer execution until necessary.
//! Wrapped value is just a box pointing to the constructor function.
//!
//! Due to semantical laziness,
//! [`LazyInstance::replace`] and [`LazyInstance::discard_first`]/[`LazyInstance::discard_second`]
//! actually fully cancel the "unnecessary" computation.
//!
//! For stackless execution see [`super::stackless`].
use std::{cell::RefCell, rc::Rc};
use crate::func::*;
pub struct LazyInstance;
impl WeakFunctor for LazyInstance {
type F<'a, A: 'a> = Box<dyn 'a + FnOnce() -> A>;
}
impl<'a> Functor<'a> for LazyInstance {
fn fmap<A: 'a, B: 'a>(f: impl 'a + FnOnce(A) -> B, fa: Self::Fa<A>) -> Self::Fa<B> {
Box::new(|| f(fa()))
}
fn replace<A: 'a, B: 'a>(fa: Self::Fa<A>, b: B) -> Self::Fa<B> {
drop(fa);
Box::new(|| b)
}
fn void<A: 'a>(fa: Self::Fa<A>) -> Self::Fa<()> {
drop(fa);
Box::new(|| ())
}
}
impl<'a> Pure<'a> for LazyInstance {
fn pure<A: 'a>(a: A) -> Self::Fa<A> {
Box::new(|| a)
}
}
impl<'a> ApplicativeSeq<'a> for LazyInstance {
fn seq<A: 'a, B: 'a>(ff: Self::Fa<impl 'a + FnOnce(A) -> B>, fa: Self::Fa<A>) -> Self::Fa<B> {
Box::new(|| ff()(fa()))
}
}
impl<'a> ApplicativeLA2<'a> for LazyInstance {
fn la2<A: 'a, B: 'a, C: 'a>(
f: impl 'a + FnOnce(A, B) -> C,
fa: Self::Fa<A>,
fb: Self::Fa<B>,
) -> Self::Fa<C> {
Box::new(|| f(fa(), fb()))
}
}
impl<'a> ApplicativeTuple<'a> for LazyInstance {
fn tuple<A: 'a, B: 'a>((fa, fb): (Self::Fa<A>, Self::Fa<B>)) -> Self::Fa<(A, B)> {
Box::new(|| (fa(), fb()))
}
}
impl<'a> ApplicativeSelect<'a> for LazyInstance {}
impl<'a> Applicative<'a> for LazyInstance {
fn discard_first<A: 'a, B: 'a>(fa: Self::Fa<A>, fb: Self::Fa<B>) -> Self::Fa<B> {
drop(fa);
fb
}
fn discard_second<A: 'a, B: 'a>(fa: Self::Fa<A>, fb: Self::Fa<B>) -> Self::Fa<A> {
drop(fb);
fa
}
}
impl<'a> Monad<'a> for LazyInstance {
fn bind<A: 'a, B: 'a>(fa: Self::Fa<A>, f: impl 'a + FnOnce(A) -> Self::Fa<B>) -> Self::Fa<B> {
Box::new(|| f(fa())())
}
fn iterate<B: 'a>(mut f: impl Iterative<'a, T = Self, B = B>) -> Self::Fa<B> {
loop {
match f.next()() {
ControlFlow::Continue(next_f) => f = next_f,
ControlFlow::Break(b) => return Self::pure(b),
}
}
}
fn join<A: 'a>(ffa: Self::Fa<Self::Fa<A>>) -> Self::Fa<A> {
Box::new(|| ffa()())
}
}
fn unshare<'a, A: 'a + Clone>(shared: &mut Option<Box<dyn 'a + FnOnce() -> A>>) -> A {
let a = shared.take().expect(
"cannot evaluate a missing shared lazy value. probably, the shared value depends on itself",
)();
let cloned = a.clone();
*shared = Some(Box::new(|| cloned));
a
}
impl<'a> SharedFunctor<'a> for LazyInstance {
type Shared<A: 'a + Clone> = Rc<RefCell<Option<Box<dyn 'a + FnOnce() -> A>>>>;
fn share<A: 'a + Clone>(fa: Self::Fa<A>) -> Self::Shared<A> {
Rc::new(RefCell::new(Some(fa)))
}
fn unshare<A: 'a + Clone>(sa: Self::Shared<A>) -> Self::Fa<A> {
Box::new(move || unshare(&mut *sa.borrow_mut()))
}
}