Advertisement
bitshifternz

Untitled

Apr 24th, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.04 KB | None | 0 0
  1. pub struct HNil;
  2.  
  3. pub struct HCons<H, T> {
  4.     pub head: H,
  5.     pub tail: T,
  6. }
  7.  
  8. pub enum Coproduct<H, T> {
  9.     Inl(H),
  10.     Inr(T),
  11. }
  12.  
  13. pub enum CNil {}
  14.  
  15. pub trait CoproductFoldable<Folder, Output> {
  16.     fn fold(self, f: Folder) -> Output;
  17. }
  18.  
  19. impl<F, R, FTail, CH, CTail> CoproductFoldable<HCons<F, FTail>, R> for Coproduct<CH, CTail>
  20.     where F: FnOnce(CH) -> R,
  21.           CTail: CoproductFoldable<FTail, R>
  22. {
  23.     fn fold(self, f: HCons<F, FTail>) -> R {
  24.         use self::Coproduct::*;
  25.         let f_head = f.head;
  26.         let f_tail = f.tail;
  27.         match self {
  28.             Inl(r) => (f_head)(r),
  29.             Inr(rest) => rest.fold(f_tail),
  30.         }
  31.     }
  32. }
  33.  
  34. impl<F, R> CoproductFoldable<F, R> for CNil {
  35.     fn fold(self, _: F) -> R {
  36.         unreachable!()
  37.     }
  38. }
  39.  
  40. fn main() {
  41.     let co1: Coproduct<i32, Coproduct<f32, CNil>> = Coproduct::Inl(3);
  42.     let hlst = HCons { head: |_i| "int", tail: HCons { head: |_f| "float", tail: HNil }};
  43.     let folded = co1.fold(hlst);
  44.     assert_eq!(folded, "int".to_string());
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement