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
//! Implementation for boxed [`Future`]

use super::*;

use std::future::Future;
use std::pin::Pin;

impl<'a, A, B> Functor<'a, B> for Pin<Box<dyn 'a + Future<Output = A>>>
where
    A: 'a,
    B: 'a,
{
    type Inner = A;
    type Mapped = Pin<Box<dyn 'a + Future<Output = B>>>;
    fn fmap<F>(self, mut f: F) -> Self::Mapped
    where
        F: 'a + Send + FnMut(Self::Inner) -> B,
    {
        Box::pin(async move { f(self.await) })
    }
}
impl<'a, A, B> Functor<'a, B>
    for Pin<Box<dyn 'a + Future<Output = A> + Send>>
where
    A: 'a,
    B: 'a,
{
    type Inner = A;
    type Mapped = Pin<Box<dyn 'a + Future<Output = B> + Send>>;
    fn fmap<F>(self, mut f: F) -> Self::Mapped
    where
        F: 'a + Send + FnMut(Self::Inner) -> B,
    {
        Box::pin(async move { f(self.await) })
    }
}

impl<'a, A> FunctorMut<'a, A> for Pin<Box<dyn 'a + Future<Output = A>>>
where
    A: 'a,
{
    fn fmap_mut<F>(&mut self, f: F)
    where
        F: 'a + Send + FnMut(&mut Self::Inner),
    {
        let this = std::mem::replace(
            self,
            Box::pin(async move { panic!("poisoned FunctorMut") }),
        );
        *self = this.fmap_fn_mutref(f);
    }
}
impl<'a, A> FunctorMut<'a, A>
    for Pin<Box<dyn 'a + Future<Output = A> + Send>>
where
    A: 'a,
{
    fn fmap_mut<F>(&mut self, f: F)
    where
        F: 'a + Send + FnMut(&mut Self::Inner),
    {
        let this = std::mem::replace(
            self,
            Box::pin(async move { panic!("poisoned FunctorMut") }),
        );
        *self = this.fmap_fn_mutref(f);
    }
}

impl<'a, A, B> Pure<'a, B> for Pin<Box<dyn 'a + Future<Output = A>>>
where
    A: 'a,
    B: 'a,
{
    fn pure(b: B) -> Self::Mapped {
        Box::pin(std::future::ready(b))
    }
}
impl<'a, A, B> Pure<'a, B>
    for Pin<Box<dyn 'a + Future<Output = A> + Send>>
where
    A: 'a,
    B: 'a + Send,
{
    fn pure(b: B) -> Self::Mapped {
        Box::pin(std::future::ready(b))
    }
}

impl<'a, A, B> Monad<'a, B> for Pin<Box<dyn 'a + Future<Output = A>>>
where
    A: 'a,
    B: 'a,
{
    fn bind<F>(self, mut f: F) -> Self::Mapped
    where
        F: 'a + Send + FnMut(Self::Inner) -> Self::Mapped,
    {
        Box::pin(async move { f(self.await).await })
    }
}
impl<'a, A, B> Monad<'a, B>
    for Pin<Box<dyn 'a + Future<Output = A> + Send>>
where
    A: 'a + Send,
    B: 'a + Send,
{
    fn bind<F>(self, mut f: F) -> Self::Mapped
    where
        F: 'a + Send + FnMut(Self::Inner) -> Self::Mapped,
    {
        Box::pin(async move { f(self.await).await })
    }
}