Skip to content

Instantly share code, notes, and snippets.

@swuecho
Forked from anonymous/playground.rs
Created December 14, 2017 17:17
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 swuecho/4eec534f3326c25b93bf2d3207768aab to your computer and use it in GitHub Desktop.
Save swuecho/4eec534f3326c25b93bf2d3207768aab to your computer and use it in GitHub Desktop.
Rust code shared from the playground
fn main () {
let number: f64 = 20.;
// Perform a pipeline of options.
let result = Some(number)
.map(inverse) // Described below.
.map(double)
.map(inverse)
.and_then(log) // Described below.
.map(square)
.and_then(sqrt);
// Extract the result.
match result {
Some(x) => println!("Result was {}.", x),
None => println!("This failed.")
}
}
// You can ignore these.
fn log(value: f64) -> Option<f64> {
match value.log2() {
x if x.is_normal() => Some(x),
_ => None
}
}
fn sqrt(value: f64) -> Option<f64> {
match value.sqrt() {
x if x.is_normal() => Some(x),
_ => None
}
}
fn double(value: f64) -> f64 {
value * 2.
}
fn square(value: f64) -> f64 {
value.powi(2 as i32)
}
fn inverse(value: f64) -> f64 {
value * -1.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment