4 /// A number, or nothing
5 pub enum NumberOrNothing {
9 use self::NumberOrNothing::{Number,Nothing};
11 /// Compute the minimum element of the vector
12 pub fn vec_min(v: Vec<i32>) -> NumberOrNothing {
13 let mut min = Nothing;
15 min = Number(match min {
17 Number(n) => std::cmp::min(n, e)
23 /// Compute the sum of elements in the vector
24 pub fn vec_sum(v: Vec<i32>) -> i32 {
32 /// Print all elements in the vector
33 pub fn vec_print(v: Vec<i32>) {
41 // A polymorphic (generic) "some value, or no value"
42 pub enum SomethingOrNothing<T> {
46 pub use self::SomethingOrNothing::*;
47 type NumberOrNothing = SomethingOrNothing<i32>;
49 /// This trait is used to compute the minimum of two elements of the given type
50 pub trait Minimum : Copy {
51 fn min(self, b: Self) -> Self;
54 /// Return the minimum element of the vector
55 pub fn vec_min<T: Minimum>(v: Vec<T>) -> SomethingOrNothing<T> {
56 let mut min = Nothing;
58 min = Something(match min {
60 Something(n) => e.min(n)
66 /// We can compute the minimum of two integers
67 impl Minimum for i32 {
68 fn min(self, b: Self) -> Self {
69 if self < b { self } else { b }
73 /// Sample program to call vec_min
74 impl NumberOrNothing {
77 Nothing => println!("The number is: <nothing>"),
78 Something(n) => println!("The number is: {}", n),
82 fn read_vec() -> Vec<i32> {
87 let min = vec_min(vec);
91 // Now, all the same for calling it on f32
92 impl Minimum for f32 {
93 fn min(self, b: Self) -> Self {
94 if self < b { self } else { b }
98 impl SomethingOrNothing<f32> {
99 pub fn print_f32(self) {
101 Nothing => println!("The number is: <nothing>"),
102 Something(n) => println!("The number is: {}", n),
107 fn read_vec_f32() -> Vec<f32> {
108 vec![18.01,5.2,7.1,3.,9.2,27.123]
111 let vec = read_vec_f32();
112 let min = vec_min(vec);
116 /// Add a `Display` implementation to `SomethingOrNothing`
118 impl<T: fmt::Display> fmt::Display for SomethingOrNothing<T> {
119 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
121 Something(ref t) => t.fmt(f),
122 Nothing => "Nothing".fmt(f),