Last active
December 2, 2017 21:15
-
-
Save sallar/845a214aa2d617cf4801d287aaebdcf3 to your computer and use it in GitHub Desktop.
Rust Learning
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
enum SomethingOrNothing<T> { | |
Something(T), | |
Nothing, | |
} | |
use self::SomethingOrNothing::*; | |
use std::io::prelude::*; | |
use std::io; | |
pub trait Minimum: Copy { | |
fn min(self, b: Self) -> Self; | |
} | |
fn vec_min<T: Minimum>(vec: Vec<T>) -> SomethingOrNothing<T> { | |
let mut min = Nothing; | |
for el in vec { | |
min = Something(match min { | |
Nothing => el, | |
Something(n) => el.min(n), | |
}) | |
} | |
min | |
} | |
impl Minimum for i32 { | |
fn min(self, b: Self) -> Self { | |
if self < b { self } else { b } | |
} | |
} | |
impl SomethingOrNothing<i32> { | |
pub fn print(self) { | |
match self { | |
Nothing => println!("The number is: <nothing>"), | |
Something(n) => println!("The number is: {}", n), | |
} | |
} | |
} | |
fn read_vec() -> Vec<i32> { | |
let mut vec: Vec<i32> = Vec::<i32>::new(); | |
let stdin = io::stdin(); | |
println!("Enter a list of numbers, one per line. End with Ctrl-D (Linux) or Ctrl-Z (Windows)."); | |
for line in stdin.lock().lines() { | |
let line = line.unwrap(); | |
match line.trim().parse::<i32>() { | |
Ok(num) => vec.push(num), | |
Err(_) => println!("What did I say about numbers?"), | |
} | |
} | |
vec | |
} | |
fn main() { | |
let vec = read_vec(); | |
let min = vec_min(vec); | |
min.print(); | |
} |
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
use std::cmp; | |
fn vec_min(vec: &Vec<i32>) -> Option<i32> { | |
let mut min = None; | |
for el in vec.iter() { | |
min = Some(match min { | |
None => *el, | |
Some(n) => cmp::min(n, *el), | |
}) | |
} | |
min | |
} | |
fn main() { | |
let v = vec![5, 4, 3, 2, 1]; | |
let first = &v[0]; | |
vec_min(&v); | |
vec_min(&v); | |
println!("The first element is: {}", *first); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment