Created
December 14, 2017 17:17
-
-
Save anonymous/346531e03b12888bfe38a5a8f282eb2b to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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