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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! Module that holds Coproduct data structures, traits, and implementations
//!
//! Think of "Coproduct" as ad-hoc enums; allowing you to do something like this
//!
//! ```
//! # #[macro_use] extern crate frunk; use frunk::coproduct::*; fn main() {
//! type I32Bool = Coproduct!(i32, bool);
//! let co1: I32Bool = into_coproduct(3);
//! let co2: I32Bool = into_coproduct(true);
//!
//! // Getting stuff
//! let get_from_1a: Option<&i32> = co1.get();
//! let get_from_1b: Option<&bool> = co1.get();
//! assert_eq!(get_from_1a, Some(&3));
//! assert_eq!(get_from_1b, None);
//!
//! let get_from_2a: Option<&i32> = co2.get();
//! let get_from_2b: Option<&bool> = co2.get();
//! assert_eq!(get_from_2a, None);
//! assert_eq!(get_from_2b, Some(&true));
//! # }
//! ```
//!
//! Or, if you want to "fold" over all possible values of a coproduct
//!
//! ```
//! # #[macro_use] extern crate frunk;
//! # #[macro_use] extern crate frunk_core;
//! # use frunk::hlist::*;
//! # use frunk::coproduct::*; fn main() {
//! # type I32Bool = Coproduct!(i32, bool);
//! # let co1: I32Bool = into_coproduct(3);
//! # let co2: I32Bool = into_coproduct(true);
//! let folder = hlist![
//!   |&i| format!("i32 {}", i),
//!   |&b| String::from(if b { "t" } else { "f" })
//! ];
//!
//! assert_eq!(co1.as_ref().fold(&folder), "i32 3".to_string());
//! assert_eq!(co2.as_ref().fold(&folder), "t".to_string());
//!
//! // There is also a value consuming-variant of fold
//!
//! let folded = co1.fold(hlist![
//!   |i| format!("i32 {}", i),
//!   |b| String::from(if b { "t" } else { "f" })
//! ]);
//! assert_eq!(folded, "i32 3".to_string());
//! # }
//! ```

use frunk_core::hlist::*;

/// Enum type representing a Coproduct. Think of this as a Result, but capable
/// of supporting any arbitrary number of types instead of just 2.
///
/// To consctruct a Coproduct, you would typically declare a type using the `Coproduct!` type
/// macro and then use the `into_coproduct` method.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate frunk; use frunk::coproduct::*; fn main() {
/// type I32Bool = Coproduct!(i32, bool);
/// let co1: I32Bool = into_coproduct(3);
/// let get_from_1a: Option<&i32> = co1.get();
/// let get_from_1b: Option<&bool> = co1.get();
/// assert_eq!(get_from_1a, Some(&3));
/// assert_eq!(get_from_1b, None);
/// # }
/// ```
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord)]
pub enum Coproduct<H, T> {
    /// Coproduct is either H or T, in this case, it is H
    Inl(H),
    /// Coproduct is either H or T, in this case, it is T
    Inr(T),
}

/// Phantom type for signature purposes only (has no value)
///
/// Used by the macro to terminate the Coproduct type signature
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord)]
pub enum CNil {}

/// Returns a type signature for a Coproduct of the provided types
///
/// This is a type macro (introduced in Rust 1.13) that makes it easier
/// to write nested type signatures.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate frunk; use frunk::coproduct::*; fn main() {
/// type I32Bool = Coproduct!(i32, bool);
/// let co1: I32Bool = into_coproduct(3);
/// # }
/// ```
#[macro_export]
macro_rules! Coproduct {
    // Nothing
    () => { $crate::coproduct::CNil };

    // Just a single item
    ($single: ty) => {
        $crate::coproduct::Coproduct<$single, CNil>
    };

    ($first: ty, $( $repeated: ty ), +) => {
        $crate::coproduct::Coproduct<$first, Coproduct!($($repeated), *)>
    };

    // <-- Forward trailing comma variants
    ($single: ty,) => {
        Coproduct![$single]
    };

    ($first: ty, $( $repeated: ty, ) +) => {
        Coproduct![$first, $($repeated),*]
    };
    // Forward trailing comma variants -->
}

// <-- For turning something into a Coproduct
pub trait IntoCoproduct<InsertType, Index> {
    fn into(to_insert: InsertType) -> Self;
}

impl<I, Tail> IntoCoproduct<I, Here> for Coproduct<I, Tail> {
    fn into(to_insert: I) -> Self {
        Coproduct::Inl(to_insert)
    }
}

impl<Head, I, Tail, TailIndex> IntoCoproduct<I, There<TailIndex>> for Coproduct<Head, Tail>
    where Tail: IntoCoproduct<I, TailIndex>
{
    fn into(to_insert: I) -> Self {
        let tail_inserted = <Tail as IntoCoproduct<I, TailIndex>>::into(to_insert);
        Coproduct::Inr(tail_inserted)
    }
}

/// Function for returning a Coproduct from a given type
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate frunk; use frunk::coproduct::*; fn main() {
/// type I32Bool = Coproduct!(i32, f32);
/// let co1: I32Bool = into_coproduct(42f32);
/// let get_from_1a: Option<&i32> = co1.get();
/// let get_from_1b: Option<&f32> = co1.get();
/// assert_eq!(get_from_1a, None);
/// assert_eq!(get_from_1b, Some(&42f32));
/// # }
/// ```
pub fn into_coproduct<C, I, Index>(to_into: I) -> C
    where C: IntoCoproduct<I, Index>
{
    <C as IntoCoproduct<I, Index>>::into(to_into)
}
// For turning something into a Coproduct -->

/// Trait for retrieving a coproduct element by type
pub trait CoproductSelector<S, I> {
    fn get(&self) -> Option<&S>;
}

impl<Head, Tail> CoproductSelector<Head, Here> for Coproduct<Head, Tail> {
    fn get(&self) -> Option<&Head> {
        use self::Coproduct::*;
        match *self {
            Inl(ref thing) => Some(thing),
            _ => None, // Impossible
        }
    }
}

impl<Head, FromTail, Tail, TailIndex> CoproductSelector<FromTail, There<TailIndex>>
    for Coproduct<Head, Tail>
    where Tail: CoproductSelector<FromTail, TailIndex>
{
    fn get(&self) -> Option<&FromTail> {
        use self::Coproduct::*;
        match *self {
            Inr(ref rest) => rest.get(),
            _ => None, // Impossible
        }
    }
}

/// Trait for implementing "folding" a Coproduct into a value.
///
/// The Folder should be an HList of closures that correspond (in order, for now..) to the
/// types used in declaring the Coproduct type.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate frunk;
/// # use frunk::coproduct::*;
/// # use frunk::hlist::*; fn main() {
/// type I32StrBool = Coproduct!(i32, f32, bool);
///
/// let co1: I32StrBool = into_coproduct(3);
/// let co2: I32StrBool = into_coproduct(true);
/// let co3: I32StrBool = into_coproduct(42f32);
///
/// let folder = hlist![|&i| format!("int {}", i),
///                     |&f| format!("float {}", f),
///                     |&b| (if b { "t" } else { "f" }).to_string()];
///
/// assert_eq!(co1.as_ref().fold(&folder), "int 3".to_string());
/// assert_eq!(co2.as_ref().fold(&folder), "t".to_string());
/// assert_eq!(co3.as_ref().fold(&folder), "float 42".to_string());
/// # }
/// ```
pub trait CoproductFoldable<Folder, Output> {
    fn fold(self, f: Folder) -> Output;
}

impl<F, R, FTail, CH, CTail> CoproductFoldable<HCons<F, FTail>, R> for Coproduct<CH, CTail>
    where F: FnOnce(CH) -> R,
          CTail: CoproductFoldable<FTail, R>
{
    fn fold(self, f: HCons<F, FTail>) -> R {
        use self::Coproduct::*;
        let f_head = f.head;
        let f_tail = f.tail;
        match self {
            Inl(r) => (f_head)(r),
            Inr(rest) => rest.fold(f_tail),
        }
    }
}

impl<'a, F, R, FTail, CH, CTail> CoproductFoldable<&'a HCons<F, FTail>, R> for &'a Coproduct<CH, CTail>
    where F: Fn(&'a CH) -> R,
          &'a CTail: CoproductFoldable<&'a FTail, R>
{
    fn fold(self, f: &'a HCons<F, FTail>) -> R {
        use self::Coproduct::*;
        let ref f_head = f.head;
        let ref f_tail = f.tail;
        match *self {
            Inl(ref r) => (f_head)(r),
            Inr(ref rest) => <&'a CTail as CoproductFoldable<&'a FTail, R>>::fold(rest, f_tail),
        }
    }
}

/// This is literally impossible; CNil is not instantiable
#[doc(hidden)]
impl<F, R> CoproductFoldable<F, R> for CNil {
    fn fold(self, _: F) -> R {
        unreachable!()
    }
}

/// This is literally impossible; &CNil is not instantiable
#[doc(hidden)]
impl<'a, F, R> CoproductFoldable<&'a F, R> for &'a CNil {
    fn fold(self, _: &'a F) -> R {
        unreachable!()
    }
}

impl <CH, CTail> AsRef<Coproduct<CH, CTail>> for Coproduct<CH, CTail> {
    fn as_ref(&self) -> &Coproduct<CH, CTail> {
        self
    }
}

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

    #[test]
    fn test_into_coproduct() {
        type I32StrBool = Coproduct!(i32, &'static str, bool);

        let co1: I32StrBool = into_coproduct(3);
        assert_eq!(co1, Inl(3));
        let get_from_1a: Option<&i32> = co1.get();
        let get_from_1b: Option<&bool> = co1.get();
        assert_eq!(get_from_1a, Some(&3));
        assert_eq!(get_from_1b, None);


        let co2: I32StrBool = into_coproduct(false);
        assert_eq!(co2, Inr(Inr(Inl(false))));
        let get_from_2a: Option<&i32> = co2.get();
        let get_from_2b: Option<&bool> = co2.get();
        assert_eq!(get_from_2a, None);
        assert_eq!(get_from_2b, Some(&false));
    }

    #[test]
    fn test_coproduct_fold_consuming() {
        type I32StrBool = Coproduct!(i32, f32, bool);

        let co1: I32StrBool = into_coproduct(3);
        let folded = co1.fold(hlist![|i| format!("int {}", i),
                                      |f| format!("float {}", f),
                                      |b| (if b { "t" } else { "f" }).to_string()]);

        assert_eq!(folded, "int 3".to_string());
    }

    #[test]
    fn test_coproduct_fold_non_consuming() {
        type I32StrBool = Coproduct!(i32, f32, bool);

        let co1: I32StrBool = into_coproduct(3);
        let co2: I32StrBool = into_coproduct(true);
        let co3: I32StrBool = into_coproduct(42f32);

        let folder = hlist![|&i| format!("int {}", i),
                            |&f| format!("float {}", f),
                            |&b| (if b { "t" } else { "f" }).to_string()];

        assert_eq!(co1.as_ref().fold(&folder), "int 3".to_string());
        assert_eq!(co2.as_ref().fold(&folder), "t".to_string());
        assert_eq!(co3.as_ref().fold(&folder), "float 42".to_string());
    }
}