Implement Add on Option types

This will allow you to use the + operator to add together any two
Options, assuming that the contents of each Option likewise implement
+. So Some(4) + Some(1) == Some(5), and adding with None leaves the
other value unchanged.

This might be monoidic? I don't know what that word means!
This commit is contained in:
Ben Striegel 2013-03-11 22:46:16 -04:00
parent a6bb4a0f1a
commit a21b43c6bb
2 changed files with 40 additions and 0 deletions

View file

@ -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);
}
}