Skip to content

Instantly share code, notes, and snippets.

@enricostano
Last active December 3, 2015 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enricostano/45fc772a8a6d928925b8 to your computer and use it in GitHub Desktop.
Save enricostano/45fc772a8a6d928925b8 to your computer and use it in GitHub Desktop.
use std::cmp::Ordering;
#[derive(Clone, Eq, PartialEq)]
struct Element {
weight: usize
}
impl Ord for Element {
fn cmp(&self, other: &Element) -> Ordering {
let ow = other.weight;
self.weight.cmp(&ow)
}
}
impl PartialOrd for Element {
fn partial_cmp(&self, other: &Element) -> Option<Ordering> {
Some(self.cmp(other))
}
}
struct BranchPoint<Element: Ord> {
children: Vec<Element>,
weight: usize
}
fn create_tree<Element>(elements: &[Element], num_branches: usize) -> BranchPoint<Element> where Element: Clone + Ord {
if num_branches < 2 {
panic!("Number of branches should be at least 2, found: {}", num_branches);
}
let num_elements = elements.len();
match num_elements {
0 => return BranchPoint { children: Vec::new(), weight: 0 },
1 => return BranchPoint { children: Vec::from(elements), weight: elements.first().unwrap().weight },
_ => return BranchPoint { children: Vec::new(), weight: 0 },
}
}
#[test]
#[should_panic]
fn it_does_not_accept_num_branch_smaller_than_2() {
let alphabet = vec![0];
let v = vec![Element { weight: 15 }];
create_tree(&v, alphabet.len() as usize);
}
#[test]
fn when_0_elements_returns_empty_branch_point() {
let alphabet = vec![1, 2];
let v: Vec<Element> = Vec::new();
let tree = create_tree(&v, alphabet.len() as usize);
assert!(tree.children.is_empty());
assert_eq!(tree.weight, 0);
}
#[test]
fn when_1_elements_returns_1_branch_point() {
let alphabet = vec![1, 2];
let v = vec![Element { weight: 15 }];
let tree = create_tree(&v, alphabet.len() as usize);
assert_eq!(tree.children.len(), 1);
assert_eq!(tree.weight, 13);
}
#[test]
fn trying_out_ord() {
let el1 = Element { weight: 15 };
let el2 = Element { weight: 15 };
assert_eq!(el1.cmp(&el2), Ordering::Equal);
}
@enricostano
Copy link
Author

src/lib.rs:35:74: 35:106 error: attempted access of field `weight` on type `&Element`, but no field with that name was found
src/lib.rs:35         1 => return BranchPoint { children: Vec::from(elements), weight: elements.first().unwrap().weight },
                                                                                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment