radn-rs/src/func/instances/future.rs

127 lines
3.4 KiB
Rust

//! Async [Monad] based on [`Pin<Box<dyn Future>>`] (see: [`Pin`], [`Box::pin`], [`Future`]).
//! This generally allows just using [`.await`] on wrapped instances.
//!
//! For sync, see [`solo`].
//!
//! For fallible futures, see [`tryfuture`].
//!
//! [`solo`]: super::solo
//! [`tryfuture`]: super::tryfuture
//! [`.await`]: https://doc.rust-lang.org/std/keyword.await.html
use std::{future::Future, pin::Pin};
use futures::{
future::{join, select, Either, Shared},
join, FutureExt,
};
use crate::func::class_prelude::*;
pub struct FutureInstance;
impl WeakFunctorAny for FutureInstance {
type FAny<'a, A: 'a> = Pin<Box<dyn 'a + Future<Output = A>>>;
}
impl<'a> Functor<'a> for FutureInstance {
fn fmap<A: 'a, B: 'a>(fa: Self::F<A>, f: impl 'a + FnOnce(A) -> B) -> Self::F<B> {
Box::pin(async { f(fa.await) })
}
fn replace<A: 'a, B: 'a>(fa: Self::F<A>, b: B) -> Self::F<B> {
Box::pin(async {
fa.await;
b
})
}
}
impl<'a> Pure<'a> for FutureInstance {
fn pure<A: 'a>(a: A) -> Self::F<A> {
Box::pin(async { a })
}
}
impl<'a> ApplicativeSeq<'a> for FutureInstance {
fn seq<A: 'a, B: 'a>(ff: Self::F<impl 'a + FnOnce(A) -> B>, fa: Self::F<A>) -> Self::F<B> {
Box::pin(async {
let (f, a) = join!(ff, fa);
f(a)
})
}
}
impl<'a> ApplicativeLA2<'a> for FutureInstance {
fn la2<A: 'a, B: 'a, C: 'a>(
fa: Self::F<A>,
fb: Self::F<B>,
f: impl 'a + FnOnce(A, B) -> C,
) -> Self::F<C> {
Box::pin(async {
let (a, b) = join!(fa, fb);
f(a, b)
})
}
}
impl<'a> ApplicativeTuple<'a> for FutureInstance {
fn tuple<A: 'a, B: 'a>((fa, fb): (Self::F<A>, Self::F<B>)) -> Self::F<(A, B)> {
Box::pin(join(fa, fb))
}
}
impl<'a> ApplicativeSelect<'a> for FutureInstance {
fn select<A: 'a, B: 'a>(fa: Self::F<A>, fb: Self::F<B>) -> SelectedWrapped<'a, A, B, Self> {
Box::pin(async {
match select(fa, fb).await {
Either::Left((a, fb)) => Selected::A(a, fb),
Either::Right((b, fa)) => Selected::B(fa, b),
}
})
}
}
impl<'a> Applicative<'a> for FutureInstance {
fn discard_first<A: 'a, B: 'a>(fa: Self::F<A>, fb: Self::F<B>) -> Self::F<B> {
Box::pin(async { join!(fa, fb).1 })
}
fn discard_second<A: 'a, B: 'a>(fa: Self::F<A>, fb: Self::F<B>) -> Self::F<A> {
Box::pin(async { join!(fa, fb).0 })
}
}
impl<'a> Monad<'a> for FutureInstance {
fn bind<A: 'a, B: 'a>(fa: Self::F<A>, f: impl 'a + FnOnce(A) -> Self::F<B>) -> Self::F<B> {
Box::pin(async { f(fa.await).await })
}
fn iterate<B: 'a>(mut f: impl Iterative<'a, T = Self, B = B>) -> Self::F<B> {
Box::pin(async move {
loop {
match f.next().await {
ControlFlow::Continue(next_f) => f = next_f,
ControlFlow::Break(b) => return b,
}
}
})
}
fn join<A: 'a>(ffa: Self::F<Self::F<A>>) -> Self::F<A> {
Box::pin(async { ffa.await.await })
}
}
impl<'a> SharedFunctor<'a> for FutureInstance {
type Shared<A: 'a + Clone> = Shared<Pin<Box<dyn 'a + Future<Output = A>>>>;
fn share<A: 'a + Clone>(fa: Self::F<A>) -> Self::Shared<A> {
fa.shared()
}
fn unshare<A: 'a + Clone>(sa: Self::Shared<A>) -> Self::F<A> {
Box::pin(sa)
}
}