//! Async [Monad] based on [`Pin>`] (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>>; } impl<'a> Functor<'a> for FutureInstance { fn fmap(fa: Self::F, f: impl 'a + FnOnce(A) -> B) -> Self::F { Box::pin(async { f(fa.await) }) } fn replace(fa: Self::F, b: B) -> Self::F { Box::pin(async { fa.await; b }) } } impl<'a> Pure<'a> for FutureInstance { fn pure(a: A) -> Self::F { Box::pin(async { a }) } } impl<'a> ApplicativeSeq<'a> for FutureInstance { fn seq(ff: Self::F B>, fa: Self::F) -> Self::F { Box::pin(async { let (f, a) = join!(ff, fa); f(a) }) } } impl<'a> ApplicativeLA2<'a> for FutureInstance { fn la2( fa: Self::F, fb: Self::F, f: impl 'a + FnOnce(A, B) -> C, ) -> Self::F { Box::pin(async { let (a, b) = join!(fa, fb); f(a, b) }) } } impl<'a> ApplicativeTuple<'a> for FutureInstance { fn tuple((fa, fb): (Self::F, Self::F)) -> Self::F<(A, B)> { Box::pin(join(fa, fb)) } } impl<'a> ApplicativeSelect<'a> for FutureInstance { fn select(fa: Self::F, fb: Self::F) -> 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(fa: Self::F, fb: Self::F) -> Self::F { Box::pin(async { join!(fa, fb).1 }) } fn discard_second(fa: Self::F, fb: Self::F) -> Self::F { Box::pin(async { join!(fa, fb).0 }) } } impl<'a> Monad<'a> for FutureInstance { fn bind(fa: Self::F, f: impl 'a + FnOnce(A) -> Self::F) -> Self::F { Box::pin(async { f(fa.await).await }) } fn iterate(mut f: impl Iterative<'a, T = Self, B = B>) -> Self::F { Box::pin(async move { loop { match f.next().await { ControlFlow::Continue(next_f) => f = next_f, ControlFlow::Break(b) => return b, } } }) } fn join(ffa: Self::F>) -> Self::F { Box::pin(async { ffa.await.await }) } } impl<'a> SharedFunctor<'a> for FutureInstance { type Shared = Shared>>>; fn share(fa: Self::F) -> Self::Shared { fa.shared() } fn unshare(sa: Self::Shared) -> Self::F { Box::pin(sa) } }