mwchase

This is almost useful

Jul 13th, 2017
816
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.74 KB | None | 0 0
  1. fn main() {
  2.     println!("{}", (1, (2, (4, Empty()))).get(2));
  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(&self, index: usize) -> &T {
  14.         match index {
  15.             0 => self.get_head(),
  16.             x => self.get_tail().get(x - 1)
  17.         }
  18.     }
  19. }
  20.  
  21. impl<T, C:Cons<T>> Cons<T> for (T, C) {
  22.     type Tail = C;
  23.    
  24.     fn get_head(&self) -> &T {
  25.         &self.0
  26.     }
  27.     fn get_tail(&self) -> &Self::Tail {
  28.         &self.1
  29.     }
  30. }
  31.  
  32. impl<T> Cons<T> for Empty {
  33.     type Tail = Empty;
  34.    
  35.     fn get_head(&self) -> &T {
  36.         panic!()
  37.     }
  38.     fn get_tail(&self) -> &Self::Tail {
  39.         panic!()
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment