Skip to content

Instantly share code, notes, and snippets.

@mwhittaker
Created June 8, 2014 02:11
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 mwhittaker/f036cab4abc5f2ab3dc0 to your computer and use it in GitHub Desktop.
Save mwhittaker/f036cab4abc5f2ab3dc0 to your computer and use it in GitHub Desktop.
Rust Option Bind
// Option bind for rust 0.10
fn inv(f: f32) -> Option<f32> {
if f == 0.0 {
None
}
else {
Some(1.0 / f)
}
}
fn bind<A, B>(o: Option<A>, f: fn(A) -> Option<B>) -> Option<B> {
match o {
Some(x) => f(x),
None => None
}
}
fn main() {
println!("{}", bind(Some(2.0), inv))
println!("{}", bind(Some(0.0), inv))
}
@mwhittaker
Copy link
Author

To build and run, enter

rustc bind.rs && ./bind

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