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
use std::future::IntoFuture;
use futures::{executor::LocalPool, future::LocalBoxFuture, Future};
use crate::{Apply, Bind, Functor, Pure};
pub struct Effect<'a, A> {
future: LocalBoxFuture<'a, A>,
}
impl<'a, A> core::fmt::Debug for Effect<'a, A> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::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: Box::pin(future),
}
}
}
impl<'a, A> Bind<'a, A> for Effect<'a, A>
where
A: 'a,
{
type Target<T> = Effect<'a, T>;
fn bind<B, F>(self, f: F) -> Self::Target<B>
where
F: Fn(A) -> Self::Target<B> + 'a,
{
async move { f(self.await).await }.into()
}
}
impl<'a, A> Functor<'a, A> for Effect<'a, A>
where
A: 'a,
{
type Target<T> = Effect<'a, T>;
fn fmap<B, F>(self, f: F) -> Self::Target<B>
where
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 {
async move { value }.into()
}
}
impl<'a, A> Apply<'a, A> for Effect<'a, A>
where
A: 'a,
{
type Target<T> = Effect<'a, T> where T:'a;
fn apply<B>(
self,
f: <Self as Apply<'a, A>>::Target<crate::apply::ApplyFn<'a, A, B>>,
) -> <Self as Apply<'a, A>>::Target<B>
where
B: 'a,
{
async move {
let func = f.await;
let arg = self.await;
func.apply(arg)
}
.into()
}
}
pub fn run_effect<'a, A>(effect: Effect<'a, A>) -> A {
LocalPool::new().run_until(effect.into_future())
}