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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use std::{fmt::Debug, future::IntoFuture};

use futures::{
    future::{Either, LocalBoxFuture},
    Future, FutureExt,
};

use higher::{apply::ApplyFn, Apply, Bifunctor, Bind, Functor, Pure};

/// An effect monad.
///
/// This is essentially just a newtype for a boxed [`Future`](Future) that
/// implements [`Monad`](higher::Monad), so that you can treat your
/// [`Future`](Future)s like they're [`Monad`](higher::Monad)s with the
/// [`run!`](higher::run) macro and all the category theory you like.
///
/// To turn a [`Future`](Future) into an [`Effect`](Effect) monad, use
/// [`From`](From) and [`Into`](Into):
///
/// ```
/// # use higher_effect::Effect;
/// let my_future = async { "Hello Joe!" };
/// let my_effect = Effect::from(my_future);
/// ```
///
/// Effects can be awaited like they're futures, because they implement
/// [`IntoFuture`](IntoFuture):
///
/// ```
/// # use higher_effect::Effect;
/// # let mut pool = futures::executor::LocalPool::new();
/// # let my_effect = Effect::from(async { "Hello Joe!" });
/// # let async_block = async {
/// assert_eq!(my_effect.await, "Hello Joe!");
/// # };
/// # pool.run_until(async_block);
/// ```
///
/// You can compose effects using the [`run!`](higher::run) macro:
///
/// ```
/// # use higher::{run, Pure};
/// # use higher_effect::Effect;
/// # let mut pool = futures::executor::LocalPool::new();
/// # let async_block = async {
/// run! {
///     // Lift the value 1 into the Effect monad
///     x <= Effect::pure(1);
///     // Create an effect from an async block returning the value 2
///     y <= Effect::from(async { 2 });
///     // Perform a computation in an async block using the previously bound values
///     z <= Effect::from(async move { x + y });
///     // Compute the result and await it
///     yield x + y + z
/// }.await
/// # };
/// # assert_eq!(pool.run_until(async_block), 6);
/// ```
pub struct Effect<'a, A> {
    future: LocalBoxFuture<'a, A>,
}

impl<'a, A> Effect<'a, A> {
    /// Run the effect to completion, blocking the current thread.
    pub fn run(self) -> A {
        futures::executor::LocalPool::new().run_until(self.into_future())
    }

    /// Construct an effect that resolves immediately to the given value.
    pub fn ready(value: A) -> Self
    where
        A: 'a,
    {
        async { value }.into()
    }

    /// Runs two effects in parallel, returning the result of whichever finishes first.
    pub fn select<B>(
        eff1: Effect<'a, A>,
        eff2: Effect<'a, B>,
    ) -> Effect<'a, Either<(A, Effect<'a, B>), (B, Effect<'a, A>)>>
    where
        A: 'a,
        B: 'a,
    {
        async {
            futures::future::select(eff1.into_future(), eff2.into_future())
                .await
                .bimap(|(a, f)| (a, f.into()), |(b, f)| (b, f.into()))
        }
        .into()
    }

    /// Runs a list of effects in parallel, returning the result of whichever finishes first.
    pub fn select_all<I>(iter: I) -> Effect<'a, (A, usize, Vec<Effect<'a, A>>)>
    where
        A: 'a,
        I: IntoIterator<Item = Effect<'a, A>> + 'a,
    {
        async {
            let (result, index, remainder) =
                futures::future::select_all(iter.into_iter().map(|eff| eff.into_future())).await;
            (result, index, remainder.fmap(|f| f.into()))
        }
        .into()
    }

    /// Runs two effects in parallel, returning the results of both.
    pub fn join<B>(eff1: Effect<'a, A>, eff2: Effect<'a, B>) -> Effect<'a, (A, B)>
    where
        A: 'a,
        B: 'a,
    {
        async { futures::future::join(eff1.into_future(), eff2.into_future()).await }.into()
    }

    /// Runs three effects in parallel, returning the results of all three.
    pub fn join3<B, C>(
        eff1: Effect<'a, A>,
        eff2: Effect<'a, B>,
        eff3: Effect<'a, C>,
    ) -> Effect<'a, (A, B, C)>
    where
        A: 'a,
        B: 'a,
        C: 'a,
    {
        async {
            futures::future::join3(eff1.into_future(), eff2.into_future(), eff3.into_future()).await
        }
        .into()
    }

    /// Runs four effects in parallel, returning the results of all four.
    pub fn join4<B, C, D>(
        eff1: Effect<'a, A>,
        eff2: Effect<'a, B>,
        eff3: Effect<'a, C>,
        eff4: Effect<'a, D>,
    ) -> Effect<'a, (A, B, C, D)>
    where
        A: 'a,
        B: 'a,
        C: 'a,
        D: 'a,
    {
        async {
            futures::future::join4(
                eff1.into_future(),
                eff2.into_future(),
                eff3.into_future(),
                eff4.into_future(),
            )
            .await
        }
        .into()
    }

    /// Runs a list of effects in parallel, returning a list of their results
    /// when they have all resolved.
    pub fn join_all<I>(iter: I) -> Effect<'a, Vec<A>>
    where
        I: IntoIterator<Item = Effect<'a, A>> + 'a,
    {
        async { futures::future::join_all(iter.into_iter().map(|eff| eff.into_future())).await }
            .into()
    }
}

impl<'a, A> Debug for Effect<'a, A> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&format!("Effect<{}>", std::any::type_name::<A>()))
    }
}

impl<'a, A> IntoFuture for Effect<'a, A> {
    type Output = A;

    type IntoFuture = LocalBoxFuture<'a, A>;

    fn into_future(self) -> Self::IntoFuture {
        self.future
    }
}

impl<'a, A, F> From<F> for Effect<'a, A>
where
    F: Future<Output = A> + 'a,
{
    fn from(future: F) -> Self {
        Self {
            future: future.boxed_local(),
        }
    }
}

impl<'a, A: 'a> Bind<'a, A> for Effect<'a, A>
where
    A: Clone,
{
    fn bind<B, F>(self, f: F) -> Self::Target<B>
    where
        B: 'a,
        F: Fn(A) -> Self::Target<B> + 'a,
    {
        async move { f(self.await).await }.into()
    }
}

impl<'a, A: 'a> Functor<'a, A> for Effect<'a, A> {
    type Target<T: 'a> = Effect<'a, T>;

    fn fmap<B, F>(self, f: F) -> Self::Target<B>
    where
        B: 'a,
        F: Fn(A) -> B + 'a,
    {
        async move { f(self.await) }.into()
    }
}

impl<'a, A> Pure<A> for Effect<'a, A>
where
    A: 'a,
{
    fn pure(value: A) -> Self {
        Self::ready(value)
    }
}

impl<'a, A: 'a> Apply<'a, A> for Effect<'a, A>
where
    A: Clone,
{
    fn apply<B>(self, f: Self::Target<ApplyFn<'a, A, B>>) -> Self::Target<B>
    where
        B: 'a,
    {
        async move {
            let (func, arg) = Effect::join(f, self).await;
            func.apply_fn(arg)
        }
        .into()
    }
}

#[cfg(test)]
mod test {
    use super::Effect;
    use higher::{Pure, Traversable};

    #[test]
    fn traverse_effect() {
        let ef1 = Effect::pure(1);
        let ef2 = Effect::pure(2);
        let ef3 = Effect::pure(3);
        let efs = vec![ef1, ef2, ef3];
        let joined: Effect<'_, Vec<i32>> = efs.sequence();
        assert_eq!(joined.run(), vec![1, 2, 3]);
    }
}