Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. #[derive(Debug)]
  2. struct Cons<T, U>(T, U);
  3.  
  4. #[derive(Debug)]
  5. struct MyOption<T>(Option<T>);
  6.  
  7. trait Prepend<T>: Sized {
  8. fn prepend(self, value: T) -> Cons<Self, T>;
  9. }
  10.  
  11. impl<T, U> Prepend<U> for Cons<T, U> {
  12. fn prepend(self, value: U) -> Cons<Self, U> {
  13. Cons(self, value)
  14. }
  15. }
  16.  
  17. impl<T> Prepend<T> for T {
  18. fn prepend(self, value: T) -> Cons<Self, Self> {
  19. Cons(self, value)
  20. }
  21. }
  22.  
  23. impl<T: Iterator<Item = U>, U> Cons<T, MyOption<U>> {
  24. fn next(&mut self) -> Option<U> {
  25. match (self.1).0.take() {
  26. Some(u) => Some(u),
  27. None => self.0.next()
  28. }
  29. }
  30. }
  31.  
  32. impl<T> Iterator for Cons<MyOption<T>, MyOption<T>> {
  33. type Item = T;
  34. fn next(&mut self) -> Option<Self::Item> {
  35. match (self.1).0.take() {
  36. Some(t) => Some(t),
  37. None => (self.0).0.take()
  38. }
  39. }
  40. }
  41.  
  42. impl<T: Iterator<Item = U>, U> Iterator for Cons<Cons<T, MyOption<U>>, MyOption<U>> {
  43. type Item = U;
  44. fn next(&mut self) -> Option<Self::Item> {
  45. match (self.1).0.take() {
  46. Some(u) => Some(u),
  47. None => self.0.next()
  48. }
  49. }
  50. }
  51.  
  52. impl<T> Iterator for MyOption<T> {
  53. type Item = T;
  54. fn next(&mut self) -> Option<Self::Item> {
  55. self.0.take()
  56. }
  57. }
  58.  
  59. fn create_stack() -> impl Iterator<Item = i32> + core::fmt::Debug {
  60. MyOption(Some(0))
  61. .prepend(MyOption(Some(1)))
  62. .prepend(MyOption(Some(2)))
  63. .prepend(MyOption(Some(3)))
  64. .prepend(MyOption(Some(4)))
  65. }
  66.  
  67. fn main() {
  68. let stack = create_stack();
  69. println!("Here's the stack:");
  70. println!("{:?}", stack);
  71.  
  72. println!("Here are the items in reverse order");
  73. for item in stack {
  74. println!("{}", item);
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement