1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
//! 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 + Send> = Pin<Box<dyn 'a + Send + Future<Output = A>>>;
}

impl<'a> Functor<'a> for FutureInstance {
    fn fmap<A: 'a + Send, B: 'a + Send>(
        fa: Self::F<A>,
        f: impl 'a + Send + FnOnce(A) -> B,
    ) -> Self::F<B> {
        Box::pin(async { f(fa.await) })
    }

    fn replace<A: 'a + Send, B: 'a + Send>(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 + Send>(a: A) -> Self::F<A> {
        Box::pin(async { a })
    }
}

impl<'a> ApplicativeSeq<'a> for FutureInstance {
    fn seq<A: 'a + Send, B: 'a + Send>(
        ff: Self::F<impl 'a + Send + 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 + Send, B: 'a + Send, C: 'a + Send>(
        fa: Self::F<A>,
        fb: Self::F<B>,
        f: impl 'a + Send + 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 + Send, B: 'a + Send>((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 + Send, B: 'a + Send>(
        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 + Send, B: 'a + Send>(fa: Self::F<A>, fb: Self::F<B>) -> Self::F<B> {
        Box::pin(async { join!(fa, fb).1 })
    }

    fn discard_second<A: 'a + Send, B: 'a + Send>(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 + Send, B: 'a + Send>(
        fa: Self::F<A>,
        f: impl 'a + Send + FnOnce(A) -> Self::F<B>,
    ) -> Self::F<B> {
        Box::pin(async { f(fa.await).await })
    }

    fn iterate<B: 'a + Send>(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 + Send>(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 + Send + Sync + Clone> = Shared<Pin<Box<dyn 'a + Send + Future<Output = A>>>>;

    fn share<A: 'a + Send + Sync + Clone>(fa: Self::F<A>) -> Self::Shared<A> {
        fa.shared()
    }

    fn unshare<A: 'a + Send + Sync + Clone>(sa: Self::Shared<A>) -> Self::F<A> {
        Box::pin(sa)
    }
}

#[cfg(test)]
mod future_tests {
    use std::sync::Arc;

    use crate::func::{applicative_select::Selected, ApplicativeSelect};

    use super::{test_suite, tests, FutureInstance};

    type T = FutureInstance;

    impl<'a> tests::ToEq<'a> for T {
        type Eq<A: 'a + Send + PartialEq + std::fmt::Debug> = A;

        fn to_eq<A: 'a + Send + PartialEq + std::fmt::Debug>(fa: Self::F<A>) -> Self::Eq<A> {
            futures::executor::block_on(fa)
        }
    }

    impl<'a> test_suite::FunctorTestSuite<'a> for T {
        fn sample<A: 'a + Send, F: FnMut(Arc<dyn test_suite::WrapFunction<'a, A, Self::F<A>>>)>(
            mut f: F,
        ) {
            f(Arc::new(|a| Box::pin(futures::future::ready(a))));
        }
    }

    #[test]
    fn monad_follows_laws() {
        test_suite::monad_follows_laws::<T>().unwrap();
    }

    #[test]
    fn select_second() {
        let res = futures::executor::block_on(T::select(
            Box::pin(futures::future::pending::<i32>()),
            Box::pin(futures::future::ready(2)),
        ));
        assert!(matches!(res, Selected::B(_, 2)));
    }

    #[test]
    fn shared_follows_laws() {
        test_suite::shared_follows_laws::<T>().unwrap();
    }
}