Skip to content

Implement Add on Option types #5328

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ let unwrapped_msg = match msg {
*/

use cmp::{Eq,Ord};
use ops::Add;
use kinds::Copy;
use util;
use num::Zero;
Expand Down Expand Up @@ -85,6 +86,18 @@ impl<T:Ord> Ord for Option<T> {
}
}

impl<T: Copy + Add<T,T>> Add<Option<T>, Option<T>> for Option<T> {
#[inline(always)]
pure fn add(&self, other: &Option<T>) -> Option<T> {
match (*self, *other) {
(None, None) => None,
(_, None) => *self,
(None, _) => *other,
(Some(ref lhs), Some(ref rhs)) => Some(*lhs + *rhs)
}
}
}

#[inline(always)]
pub pure fn get<T:Copy>(opt: Option<T>) -> T {
/*!
Expand Down
27 changes: 27 additions & 0 deletions src/test/run-pass/option_addition.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
fn main() {
let foo = 1;
let bar = 2;
let foobar = foo + bar;

let nope = optint(0) + optint(0);
let somefoo = optint(foo) + optint(0);
let somebar = optint(bar) + optint(0);
let somefoobar = optint(foo) + optint(bar);

match nope {
None => (),
Some(foo) => fail!(fmt!("expected None, but found %?", foo))
}
fail_unless!(foo == somefoo.get());
fail_unless!(bar == somebar.get());
fail_unless!(foobar == somefoobar.get());
}

fn optint(in: int) -> Option<int> {
if in == 0 {
return None;
}
else {
return Some(in);
}
}