Advertisement
Guest User

Untitled

a guest
Jun 19th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. #![feature(box_syntax)]
  2.  
  3. use std::rc::Rc;
  4.  
  5. #[derive(Debug)]
  6. enum List<T: Clone> {
  7. Empty,
  8. Exist(Rc<Box<Node<T>>>),
  9. }
  10.  
  11. #[derive(Debug)]
  12. struct Node<T: Clone> {
  13. elm: T,
  14. next: Rc<List<T>>,
  15. }
  16.  
  17. trait Stack_<T> {
  18. fn new(T, Self) -> Self;
  19. fn is_empty(&self) -> bool;
  20. fn head(&self) -> Option<T>;
  21. fn tail(&self) -> Option<&Self>;
  22. fn append(&self, Self) -> Self;
  23. fn update(self, u32, T) -> Self;
  24. }
  25.  
  26. impl<T: Clone> Stack_<T> for List<T> {
  27. fn new(elm: T, next: Self) -> Self {
  28. List::Exist(Rc::new(box Node{
  29. elm: elm,
  30. next: Rc::new(next)
  31. }))
  32. }
  33.  
  34. fn is_empty(&self) -> bool {
  35. match *self {
  36. List::Empty => true,
  37. List::Exist(_) => false,
  38. }
  39. }
  40.  
  41. fn head(&self) -> Option<T> {
  42. match self {
  43. &List::Empty => None,
  44. &List::Exist(ref n) => Some(n.elm.clone())
  45. }
  46. }
  47.  
  48. fn tail(&self) -> Option<&Self> {
  49. match self {
  50. &List::Empty => None,
  51. &List::Exist(ref n) => Some(&n.next)
  52. }
  53. }
  54.  
  55. fn append(&self, l: Self) -> Self {
  56. match self {
  57. &List::Empty => l,
  58. &List::Exist(_) => {
  59. List::Exist(Rc::new(box Node{
  60. elm: self.head().unwrap(),
  61. next: Rc::new(self.tail().unwrap().append(l))
  62. }))
  63. },
  64. }
  65. }
  66.  
  67. fn update(self, i: u32, elm: T) -> Self {
  68. if self.is_empty(){
  69. List::Empty
  70. } else if i == 0 {
  71. List::new(elm, self)
  72. } else {
  73. List::new(self.head().unwrap(), self.update(i-1, elm))
  74. }
  75. }
  76. }
  77.  
  78. fn main() {
  79. let a = List::new(1, List::new(2, List::Empty));
  80. let b = List::new(3, List::new(4, List::Empty));
  81. let c = b.update(1, 3000);
  82. println!("{:?}", a.append(c));
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement