Skip to content

Instantly share code, notes, and snippets.

@NoraCodes
Created March 28, 2017 04:19
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 NoraCodes/ab8e0b226ba1ab79beb43d834126a3cb to your computer and use it in GitHub Desktop.
Save NoraCodes/ab8e0b226ba1ab79beb43d834126a3cb to your computer and use it in GitHub Desktop.
A sample of functional computations in Rust.
// 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