Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. #![feature(specialization)]
  2.  
  3. use std::ops::{Add, Sub};
  4.  
  5. #[derive(Clone, Debug)]
  6. struct One;
  7.  
  8. #[derive(Clone, Debug)]
  9. struct Int(i32);
  10.  
  11. #[derive(Clone, Debug)]
  12. struct Addition<T: Term, U: Term>(T, U);
  13.  
  14. #[derive(Clone, Debug)]
  15. struct Substraction<T: Term, U: Term>(T, U);
  16.  
  17. impl Add<One> for Int {
  18. type Output = Addition<Int, One>;
  19.  
  20. fn add(self, one: One) -> Self::Output { Addition(self, one) }
  21. }
  22.  
  23. impl Sub<One> for Int {
  24. type Output = Substraction<Int, One>;
  25.  
  26. fn sub(self, one: One) -> Self::Output { Substraction(self, one) }
  27. }
  28.  
  29. impl<T: Term, U: Term> Sub<One> for Addition<T, U> {
  30. type Output = Substraction<Addition<T, U>, One>;
  31.  
  32. fn sub(self, one: One) -> Self::Output { Substraction(self, one) }
  33. }
  34.  
  35. trait Term {
  36. type Reduced: Term;
  37.  
  38. fn reduce(self) -> Self::Reduced;
  39. }
  40.  
  41. impl Term for One {
  42. type Reduced = Self;
  43.  
  44. fn reduce(self) -> Self { self }
  45. }
  46.  
  47. impl Term for Int {
  48. type Reduced = Self;
  49.  
  50. fn reduce(self) -> Self { self }
  51. }
  52.  
  53. impl<T: Term, U: Term> Term for Addition<T, U> {
  54. type Reduced = Self;
  55.  
  56. fn reduce(self) -> Self { self }
  57. }
  58.  
  59. impl<T: Term, U: Term> Term for Substraction<T, U> {
  60. default type Reduced = Self;
  61.  
  62. default fn reduce(self) -> Self::Reduced { unimplemented!() }
  63. }
  64.  
  65. impl<T: Term> Term for Substraction<Addition<T, One>, One> {
  66. type Reduced = T;
  67.  
  68. fn reduce(self) -> Self::Reduced { (self.0).0 }
  69. }
  70.  
  71. fn main() {
  72. let x = Int(1) + One - One;
  73. println!("{:?}", x);
  74. let x = x.reduce();
  75. println!("{:?}", x);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement