4 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
7 #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
8 struct Cons<H, T: HList>(H, T);
11 // trait to classify valid HLists
13 impl HList for Nil { }
14 impl <H, T: HList> HList for Cons<H, T> { }
16 // term-level macro for HLists
17 macro_rules! hlist({ } => { Nil } ; { $ head : expr } => {
18 Cons ( $ head , Nil ) } ; {
19 $ head : expr , $ ( $ tail : expr ) , * } => {
20 Cons ( $ head , hlist ! ( $ ( $ tail ) , * ) ) } ;);
22 // type-level macro for HLists
23 macro_rules! HList({ } => { Nil } ; { $ head : ty } => {
24 Cons < $ head , Nil > } ; {
25 $ head : ty , $ ( $ tail : ty ) , * } => {
26 Cons < $ head , HList ! ( $ ( $ tail ) , * ) > } ;);
28 // nil case for HList append
29 impl <Ys: HList> Add<Ys> for Nil {
35 fn add(self, rhs: Ys) -> Ys { rhs }
38 // cons case for HList append
39 impl <Rec: HList + Sized, X, Xs: HList, Ys: HList> Add<Ys> for Cons<X, Xs>
40 where Xs: Add<Ys, Output = Rec> {
46 fn add(self, rhs: Ys) -> Cons<X, Rec> { Cons(self.0, self.1 + rhs) }
49 // type macro Expr allows us to expand the + operator appropriately
50 macro_rules! Expr({ ( $ ( $ LHS : tt ) + ) } => { Expr ! ( $ ( $ LHS ) + ) } ;
51 { HList ! [ $ ( $ LHS : tt ) * ] + $ ( $ RHS : tt ) + } => {
52 < Expr ! ( HList ! [ $ ( $ LHS ) * ] ) as Add < Expr ! (
53 $ ( $ RHS ) + ) >> :: Output } ; {
54 $ LHS : tt + $ ( $ RHS : tt ) + } => {
55 < Expr ! ( $ LHS ) as Add < Expr ! ( $ ( $ RHS ) + ) >> ::
56 Output } ; { $ LHS : ty } => { $ LHS } ;);
58 // test demonstrating term level `xs + ys` and type level `Expr!(Xs + Ys)`
60 fn aux<Xs: HList, Ys: HList>(xs: Xs, ys: Ys) -> Expr!(Xs + Ys) where
65 let xs: HList!(& str , bool , Vec < u64 >) =
66 hlist!("foo" , false , vec ! [ ]);
67 let ys: HList!(u64 , [ u8 ; 3 ] , ( )) =
68 hlist!(0 , [ 0 , 1 , 2 ] , ( ));
70 // demonstrate recursive expansion of Expr!
73 HList ! [ & str ] + HList ! [ bool ] + HList ! [ Vec < u64 >
74 ] ) + ( HList ! [ u64 ] + HList ! [ [ u8 ; 3 ] , ( ) ] ) +
75 HList ! [ ]) = aux(xs, ys);
76 assert_eq!(zs , hlist ! [
77 "foo" , false , vec ! [ ] , 0 , [ 0 , 1 , 2 ] , ( ) ])