From: Ralf Jung Date: Tue, 9 Jun 2015 20:02:15 +0000 (+0200) Subject: write code for part 03 X-Git-Url: https://git.ralfj.de/rust-101.git/commitdiff_plain/605add03bc0fe32a35fcb41d9019bdc9b306bdae?ds=sidebyside;hp=c3cbdbbd2fff81d2509b22d614343e6ca0250c09 write code for part 03 --- diff --git a/src/main.rs b/src/main.rs index b635f7e..e89f2f1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,11 +41,13 @@ // * [Part 00](part00.html) // * [Part 01](part01.html) // * [Part 02](part02.html) +// * [Part 03](part03.html) (WIP) // * (to be continued) #![allow(dead_code, unused_imports, unused_variables)] mod part00; mod part01; mod part02; +mod part03; // To actually run the code of some part (after filling in the blanks, if necessary), simply edit the `main` // function. diff --git a/src/part02.rs b/src/part02.rs index a9f9b05..7261f19 100644 --- a/src/part02.rs +++ b/src/part02.rs @@ -155,4 +155,4 @@ impl SomethingOrNothing { } } -// [index](main.html) | [previous](part01.html) | next +// [index](main.html) | [previous](part01.html) | [next](part03.html) diff --git a/src/part03.rs b/src/part03.rs new file mode 100644 index 0000000..cb0807b --- /dev/null +++ b/src/part03.rs @@ -0,0 +1,67 @@ +// Rust-101, Part 03: Input, Formatting +// ==================================== + +use std::io::prelude::*; +use std::io; + +fn read_vec() -> Vec { + let mut vec = Vec::new(); + + let stdin = io::stdin(); + println!("Enter a list of numbers, one per line. End with Ctrl-D."); + for line in stdin.lock().lines() { + let line = line.unwrap(); + match line.parse::() { + Ok(num) => vec.push(num), + Err(_) => println!("What did I say about numbers?"), + } + } + + vec +} + +enum SomethingOrNothing { + Something(T), + Nothing, +} +use self::SomethingOrNothing::{Something,Nothing}; + +trait Minimum : Copy { + fn min(a: Self, b: Self) -> Self; +} + +fn vec_min(v: &Vec) -> SomethingOrNothing { + let mut min = Nothing; + for e in v { + let e = *e; + min = Something(match min { + Nothing => e, + Something(n) => T::min(n, e) + }); + } + min +} + +impl Minimum for i32 { + fn min(a: Self, b: Self) -> Self { + ::std::cmp::min(a, b) + } +} + +use std::fmt; +impl fmt::Display for SomethingOrNothing { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + &Something(ref t) => t.fmt(f), + &Nothing => "Nothing".fmt(f), + } + } +} + +pub fn part_main() { + let vec = read_vec(); + let min = vec_min(&vec); + println!("The minimum is: {}", min); +} + +// [index](main.html) | [previous](part02.html) | next