Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub struct HNil;
- pub struct HCons<H, T> {
- pub head: H,
- pub tail: T,
- }
- pub enum Coproduct<H, T> {
- Inl(H),
- Inr(T),
- }
- pub enum CNil {}
- 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<F, R> CoproductFoldable<F, R> for CNil {
- fn fold(self, _: F) -> R {
- unreachable!()
- }
- }
- fn main() {
- let co1: Coproduct<i32, Coproduct<f32, CNil>> = Coproduct::Inl(3);
- let hlst = HCons { head: |_i| "int", tail: HCons { head: |_f| "float", tail: HNil }};
- let folded = co1.fold(hlst);
- assert_eq!(folded, "int".to_string());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement