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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#![crate_name="morphism"]
#![crate_type="lib"]

#![doc(html_root_url = "http://freebroccolo.github.io/morphism.rs/doc/morphism/")]

//! This crate provides a structure for suspended closure composition.
//! Composition is delayed and executed in a loop when a `Morphism` is
//! applied to an argument.
//!
//! The motivation for `Morphism` is to provide a means of composing
//! and evaluating an unbounded (within heap constraints) number of
//! closures without blowing the stack. In other words, `Morphism` is
//! one way to work around the lack of tail-call optimization in Rust.

use std::collections::{
    LinkedList,
    VecDeque,
};
use std::marker::{
    PhantomData,
};
use std::mem::{
    transmute,
};

/// A suspended chain of closures that behave as a function from type
/// `A` to type `B`.
///
/// When `B = A` the parameter `B` can be omitted: `Morphism<'a, A>`
/// is equivalent to `Morphism<'a, A, A>`.  This is convenient for
/// providing annotations with `Morphism::new()`.
pub struct Morphism<'a, A, B = A> {
    mfns: LinkedList<VecDeque<Box<Fn(*const ()) -> *const () + 'a>>>,
    phan: PhantomData<(A, B)>,
}

#[allow(dead_code)]
enum Void {}
impl Morphism<'static, Void> {
    /// Create the identity chain.
    ///
    /// # Example
    ///
    /// ```rust
    /// use morphism::Morphism;
    ///
    /// assert_eq!(Morphism::new::<u64>().run(42u64), 42u64);
    /// ```
    #[inline]
    pub fn new<'a, A>() -> Morphism<'a, A> {
        Morphism {
            mfns: {
                let mut mfns = LinkedList::new();
                mfns.push_back(VecDeque::new());
                mfns
            },
            phan: PhantomData,
        }
    }
}

impl<'a, B, C> Morphism<'a, B, C> {
    #[inline(always)]
    pub unsafe fn unsafe_push_front<A, F>(&mut self, f: F) -> ()
        where F: Fn(A) -> B + 'a,
    {
        match self {
            &mut Morphism {
                ref mut mfns,
                ..
            }
            => {
                // assert!(!mfns.is_empty())
                let head = mfns.front_mut().unwrap();
                let g = Box::new(move |ptr| {
                    transmute::<Box<B>, *const ()>(
                        Box::new(
                            f(*transmute::<*const (), Box<A>>(ptr))
                        )
                    )
                });
                head.push_front(g);
            },
        }
    }

    /// Attach a closure to the front of the closure chain. This corresponds to
    /// closure composition at the domain (pre-composition).
    ///
    /// # Example
    ///
    /// ```rust
    /// use morphism::Morphism;
    ///
    /// let f = Morphism::new::<Option<String>>()
    ///     .head(|x: Option<u64>| x.map(|y| y.to_string()))
    ///     .head(|x: Option<u64>| x.map(|y| y - 42u64))
    ///     .head(|x: u64| Some(x + 42u64 + 42u64));
    /// assert_eq!(f.run(0u64), Some("42".to_string()));
    /// ```
    #[inline]
    pub fn head<A, F>(self, f: F) -> Morphism<'a, A, C>
        where F: Fn(A) -> B + 'a,
    {
        let mut self0 = self;
        unsafe {
            (&mut self0).unsafe_push_front(f);
            transmute(self0)
        }
    }

    /// Mutate a given `Morphism<B, C>` by pushing a closure of type
    /// `Fn(B) -> B` onto the front of the chain.
    ///
    /// # Example
    ///
    /// ```rust
    /// use morphism::Morphism;
    ///
    /// let mut f = Morphism::new::<u64>();
    /// for i in (0..10u64) {
    ///     (&mut f).push_front(move |x| x + i);
    /// }
    /// assert_eq!(f.run(0u64), 45u64);
    /// ```
    #[inline]
    pub fn push_front<F>(&mut self, f: F) -> ()
        where F: Fn(B) -> B + 'a,
    {
        unsafe {
            self.unsafe_push_front(f)
        }
    }
}

impl<'a, A, B> Morphism<'a, A, B> {
    #[inline(always)]
    pub unsafe fn unsafe_push_back<C, F>(&mut self, f: F) -> ()
        where F: Fn(B) -> C + 'a,
    {
        match self {
            &mut Morphism {
                ref mut mfns,
                ..
            }
            => {
                // assert!(!mfns.is_empty())
                let tail = mfns.back_mut().unwrap();
                let g = Box::new(move |ptr| {
                    transmute::<Box<C>, *const ()>(
                        Box::new(
                            f(*transmute::<*const (), Box<B>>(ptr))
                        )
                    )
                });
                tail.push_back(g);
            },
        }
    }

    /// Attach a closure to the back of the closure chain. This corresponds to
    /// closure composition at the codomain (post-composition).
    ///
    /// # Example
    ///
    /// ```rust
    /// use morphism::Morphism;
    ///
    /// let f = Morphism::new::<u64>()
    ///     .tail(|x| Some(x + 42u64 + 42u64))
    ///     .tail(|x| x.map(|y| y - 42u64))
    ///     .tail(|x| x.map(|y| y.to_string()));
    /// assert_eq!(f.run(0u64), Some("42".to_string()));
    /// ```
    #[inline]
    pub fn tail<C, F>(self, f: F) -> Morphism<'a, A, C>
        where F: Fn(B) -> C + 'a,
    {
        let mut self0 = self;
        unsafe {
            (&mut self0).unsafe_push_back(f);
            transmute(self0)
        }
    }

    /// Mutate a given `Morphism<A, B>` by pushing a closure of type
    /// `Fn(B) -> B` onto the back of the chain.
    ///
    /// # Example
    ///
    /// ```rust
    /// use morphism::Morphism;
    ///
    /// let mut f = Morphism::new::<u64>();
    /// for i in (0..10u64) {
    ///     (&mut f).push_back(move |x| x + i);
    /// }
    /// assert_eq!(f.run(0u64), 45u64);
    /// ```
    #[inline]
    pub fn push_back<F>(&mut self, f: F) -> ()
        where F: Fn(B) -> B + 'a,
    {
        unsafe {
            self.unsafe_push_back(f)
        }
    }

    /// Compose one `Morphism` with another.
    ///
    /// # Example
    ///
    /// ```rust
    /// use morphism::Morphism;
    ///
    /// let mut f = Morphism::new::<u64>();
    /// for _ in (0..100000u64) {
    ///     f = f.tail(|x| x + 42u64);
    /// }
    /// // the type changes to Morphism<u64, Option<u64>> so rebind f
    /// let f = f.tail(|x| Some(x));
    ///
    /// let mut g = Morphism::new::<Option<u64>>();
    /// for _ in (0..99999u64) {
    ///     g = g.tail(|x| x.map(|y| y - 42u64));
    /// }
    /// // the type changes to Morphism<Option<u64>, String> so rebind g
    /// let g = g.tail(|x| x.map(|y| y + 1000u64).unwrap().to_string());
    ///
    /// assert_eq!(f.then(g).run(0u64), "1042".to_string());
    /// ```
    #[inline]
    pub fn then<C>(self, mut other: Morphism<'a, B, C>) -> Morphism<'a, A, C> {
        match self {
            Morphism {
                mfns: mut lhs,
                ..
            }
            => {
                match other {
                    Morphism {
                        mfns: ref mut rhs,
                        ..
                    }
                    => {
                        Morphism {
                            mfns: {
                                lhs.append(rhs);
                                lhs
                            },
                            phan: PhantomData,
                        }
                    },
                }
            },
        }
    }

    /// Given an argument, run the chain of closures in a loop and return the
    /// final result.
    #[inline]
    pub fn run(&self, x: A) -> B { unsafe {
        let mut res = transmute::<Box<A>, *const ()>(Box::new(x));
        for fns in self.mfns.iter() {
            for f in fns.iter() {
                res = f(res);
            }
        }
        *transmute::<*const (), Box<B>>(res)
    }}
}

#[cfg(test)]
mod tests
{
    use super::Morphism;

    #[test]
    fn readme() {
        let mut f = Morphism::new::<u64>();
        for _ in 0..100000u64 {
            f = f.tail(|x| x + 42u64);
        }

        let mut g = Morphism::new::<Option<u64>>();
        for _ in 0..99999u64 {
            g = g.tail(|x| x.map(|y| y - 42u64));
        }

        // type becomes Morphism<u64, (Option<u64>, bool, String)> so rebind g
        let g = g
            .tail(|x| (x.map(|y| y + 1000u64), "welp".to_string()))
            .tail(|(l, r)| (l.map(|y| y + 42u64), r))
            .tail(|(l, r)| (l, l.is_some(), r))
            .head(|x| Some(x));

        let h = f.then(g);

        assert_eq!(h.run(0u64), (Some(1084), true, "welp".to_string()));
        assert_eq!(h.run(1000u64), (Some(2084), true, "welp".to_string()));
    }

}