Created
October 13, 2019 05:00
-
-
Save gusdelact/bcd028f30f1930859fe37f7cb9340d2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(dead_code)] | |
use crate::Lista::*; | |
use std::fmt; | |
enum Lista { | |
Nodo(u32, Box<Lista>), | |
Nil, | |
} | |
impl Lista { | |
fn new() -> Lista { | |
Nil | |
} | |
fn append(self, dato: u32) -> Lista { | |
Nodo(dato, Box::new(self)) | |
} | |
fn len(&self) -> u32 { | |
match *self { | |
Nodo(_, ref tail) => 1 + tail.len(), | |
Nil => 0, | |
} | |
} | |
fn stringify(&self) -> String { | |
match *self { | |
Nodo(head, ref tail) => { | |
// `format!` is similar to `print!`, but returns a heap | |
// allocated string instead of printing to the console | |
format!("{}, {}", head, tail.stringify()) | |
}, | |
Nil => { | |
format!("Nil") | |
}, | |
} | |
} | |
} | |
impl fmt::Display for Lista { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f ,"{}",self.stringify()) | |
} | |
} | |
fn main() { | |
let mut listita = Lista::new(); | |
println!("{}", listita.len()); | |
listita = listita.append(3); | |
listita = listita.append(4); | |
println!("{}", listita.len()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment