Created
March 28, 2017 04:19
-
-
Save NoraCodes/ab8e0b226ba1ab79beb43d834126a3cb to your computer and use it in GitHub Desktop.
A sample of functional computations in Rust.
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
// Generates the first 10 odd squares, lazily. | |
// [1, 9, 25, 49, 81, 121, 169, 225, 289, 361] | |
// That is, it takes an infinite sequence of squares and | |
// checks if each subsequent one is odd, until it finds | |
// ten that are. | |
fn main() { | |
let vector: Vec<_> = (1..) // Instructions to produce | |
// integers forever | |
.map(|x| x * x) // This is now instructions for | |
// creating an infinite sequence | |
// of squares | |
.filter(|x| x % 2 != 0) // This is now instructions | |
// for an infinite sequence | |
// of _odd_ squares | |
.take(10) // This is now instructions to produce a | |
// sequence of the first 10 odd squares | |
.collect(); // Only now does the actual work occur; | |
// the instructions are executed and a | |
// vector is populated with the results. | |
println!("{:?}", vector); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment