Skip to content

Instantly share code, notes, and snippets.

@pnkfelix
Created September 2, 2013 23:14
Show Gist options
  • Save pnkfelix/6418092 to your computer and use it in GitHub Desktop.
Save pnkfelix/6418092 to your computer and use it in GitHub Desktop.
variant of merge that separates Analysis from Action.
fn merge<T: Ord + Clone>(l1: &[T], l2: &[T]) -> ~[T] {
let mut merged = ~[];
let mut l1 = l1.to_owned().move_iter().peekable();
let mut l2 = l2.to_owned().move_iter().peekable();
enum Step { Left, Right, Done }
loop {
let step = {
let a = l1.peek();
let b = l2.peek();
match (a, b) {
(None, None) => Done,
(Some(el1), None) => { merged.push(el1.clone()); Left }
(None, Some(el2)) => { merged.push(el2.clone()); Right }
(Some(el1), Some(el2)) => {
if el1 < el2 {
merged.push(el1.clone()); Left
} else {
merged.push(el2.clone()); Right
}
}
}
};
match step {
Left => l1.next(),
Right => l2.next(),
Done => return merged
};
}
}
fn main() { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment