Advertisement
mwchase

Slightly more interesting

Jul 13th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.03 KB | None | 0 0
  1. fn main() {
  2.     println!("{}", (1, (2, (4, Empty()))).get::<Succ<Succ<Zero>>>());
  3. }
  4.  
  5. struct Empty ();
  6.  
  7. trait Cons<T> {
  8.     type Tail: Cons<T>;
  9.    
  10.     fn get_head(&self) -> &T;
  11.     fn get_tail(&self) -> &Self::Tail;
  12.    
  13.     fn get<P: Peano>(&self) -> &T where Self: std::marker::Sized {
  14.         P::get(self)
  15.     }
  16. }
  17.  
  18. impl<T, C:Cons<T>> Cons<T> for (T, C) {
  19.     type Tail = C;
  20.    
  21.     fn get_head(&self) -> &T {
  22.         &self.0
  23.     }
  24.     fn get_tail(&self) -> &Self::Tail {
  25.         &self.1
  26.     }
  27. }
  28.  
  29. impl<T> Cons<T> for Empty {
  30.     type Tail = Empty;
  31.    
  32.     fn get_head(&self) -> &T {
  33.         panic!()
  34.     }
  35.     fn get_tail(&self) -> &Self::Tail {
  36.         panic!()
  37.     }
  38. }
  39.  
  40. enum Zero {}
  41.  
  42. trait Peano {
  43.     fn get<T, C: Cons<T>>(cons: &C) -> &T;
  44. }
  45.  
  46. impl Peano for Zero {
  47.    
  48.     fn get<T, C: Cons<T>>(cons: &C) -> &T {
  49.         cons.get_head()
  50.     }
  51. }
  52.  
  53. struct Succ<T>(T);
  54.  
  55. impl<P: Peano> Peano for Succ<P> {
  56.     fn get<T, C: Cons<T>>(cons: &C) -> &T {
  57.         P::get(cons.get_tail())
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement