Guest User

Untitled

a guest
May 22nd, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. enum List<T> {
  2. Node (T, Box<List<T>>),
  3. End
  4. }
  5.  
  6. impl<T> List<T> {
  7. fn new() -> List<T> {
  8. List::End
  9. }
  10.  
  11. fn len(&self) -> usize {
  12. match *self {
  13. List::Node(_, ref next) => 1 + next.len(),
  14. List::End => 0,
  15. }
  16. }
  17.  
  18. fn push(self, value: T) -> List<T> {
  19. List::Node(value, Box::new(self))
  20. }
  21.  
  22. fn pop(self) -> (Option<T>, List<T>) {
  23. match self {
  24. List::Node(value, next) => (Some(value), *next),
  25. List::End => (None, List::End),
  26. }
  27. }
  28.  
  29. fn get(&self, index: usize) -> Option<&T> {
  30. match (self, index) {
  31. (&List::Node(ref value, _), 0) => Some(value),
  32. (&List::Node(_, ref next), index) => next.get(index - 1),
  33. (&List::End, _) => None,
  34. }
  35. }
  36.  
  37. fn set(&mut self, index: usize, new_value: T) -> Option<&T> {
  38. match (self, index) {
  39. (&mut List::Node(ref mut value, _), 0) => {
  40. *value = new_value;
  41. Some(value)
  42. },
  43. (&mut List::Node(_, ref mut next), index) => next.set(index - 1, new_value),
  44. (&mut List::End, _) => None,
  45. }
  46. }
  47.  
  48. fn insert(self, index: usize, value: T) -> List<T> {
  49. match (self, index) {
  50. (tail, 0) => List::Node(value, Box::new(tail)),
  51. (List::Node(node_value, next), index) => {
  52. List::Node(
  53. node_value,
  54. Box::new(next.insert(index - 1, value))
  55. )
  56. },
  57. (List::End, _) => List::End,
  58. }
  59. }
  60.  
  61. fn value(&self) -> Option<&T> {
  62. match *self {
  63. List::Node(ref value, _) => Some(value),
  64. List::End => None
  65. }
  66. }
  67.  
  68. }
Add Comment
Please, Sign In to add comment