Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[derive(Debug)]
- struct Cons<T, U>(T, U);
- #[derive(Debug)]
- struct MyOption<T>(Option<T>);
- trait Prepend<T>: Sized {
- fn prepend(self, value: T) -> Cons<Self, T>;
- }
- impl<T, U> Prepend<U> for Cons<T, U> {
- fn prepend(self, value: U) -> Cons<Self, U> {
- Cons(self, value)
- }
- }
- impl<T> Prepend<T> for T {
- fn prepend(self, value: T) -> Cons<Self, Self> {
- Cons(self, value)
- }
- }
- impl<T: Iterator<Item = U>, U> Cons<T, MyOption<U>> {
- fn next(&mut self) -> Option<U> {
- match (self.1).0.take() {
- Some(u) => Some(u),
- None => self.0.next()
- }
- }
- }
- impl<T> Iterator for Cons<MyOption<T>, MyOption<T>> {
- type Item = T;
- fn next(&mut self) -> Option<Self::Item> {
- match (self.1).0.take() {
- Some(t) => Some(t),
- None => (self.0).0.take()
- }
- }
- }
- impl<T: Iterator<Item = U>, U> Iterator for Cons<Cons<T, MyOption<U>>, MyOption<U>> {
- type Item = U;
- fn next(&mut self) -> Option<Self::Item> {
- match (self.1).0.take() {
- Some(u) => Some(u),
- None => self.0.next()
- }
- }
- }
- impl<T> Iterator for MyOption<T> {
- type Item = T;
- fn next(&mut self) -> Option<Self::Item> {
- self.0.take()
- }
- }
- fn create_stack() -> impl Iterator<Item = i32> + core::fmt::Debug {
- MyOption(Some(0))
- .prepend(MyOption(Some(1)))
- .prepend(MyOption(Some(2)))
- .prepend(MyOption(Some(3)))
- .prepend(MyOption(Some(4)))
- }
- fn main() {
- let stack = create_stack();
- println!("Here's the stack:");
- println!("{:?}", stack);
- println!("Here are the items in reverse order");
- for item in stack {
- println!("{}", item);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement